I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in and I change the state when “onSubmit:” happened
but the Users REACT component didn’t reload .
What is wrong with this approach?
const addPlayer = async (firstName, lastName) => {
await fetch(PlayersBackend, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
"Content-Type":"application/json",
},
body: JSON.stringify({ firstName, lastName })
})
};
const AddPlayerForm=(compUsersState) =>{
const formik = useFormik(
{initialValues:{firstName: '',lastName: '',},
validate,
onSubmit: (values,{resetForm}) =>
{ addPlayer(values.firstName,values.lastName).then();
resetForm();
console.log(compUsersState.compUsersState)
compUsersState.compUsersState(p => p+1);
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="firstName">First Name</label>
<input
id="firstName"
name="firstName"
type="text"
onChange={formik.handleChange}
value={formik.values.firstName}
/>
<label htmlFor="lastName">Last Name</label>
<input
id="lastName"
name="lastName"
type="text"
onChange={formik.handleChange}
value={formik.values.lastName}
/>
<button type="submit">Add user</button>
</form>
);
};
export const Users = () => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [users, setPlayers] = useState([]);
const [,compUsersState] = useState(0);
useEffect(() => {
fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
if (error) {
//console.log(error.message);
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
if (typeof (users._embedded) !== 'undefined')
{
return (
<ul>
<AddPlayerForm compUsersState={compUsersState}/>
{users._embedded.players.map(player => (
<li className="d-flex justify-content-start" key={unique_id()}>
{player.firstName} {player.lastName}
</li>
))}
</ul>
);
}
else return (<ul> </ul> )
}
}```