In this piece of code, I am successfully retrieving data from my API. Now my problem is I am unable to assign the fetched values to my state values. Please help me :)
Here is my API call to backend which is working fine -
export const getData = (id) => {
return fetch(`${API}/course`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(id),
})
.then((response) => {
return response.json();
})
.catch((err) => console.log("error in hitting route"));
};
here is my react component which runs well :
export default function App() {
const [values, setValues] = useState({
name: "",
description: "",
price: "",
error: "",
});
const preload = (id) => {
getData(id).then((data) => {
if(data.error) {
setValues({...values, error: data.error});
}
else {
console.log("this is fetched data ", data); // I am successfully receiving this data!
setValues({
...values,
name: data.name,
description: data.description,
price: data.price,
error: false
});
console.log(values); // I am getting everything empty here e.g. name: "", description: "", price: ""
// I am unable to understand why it is not assigning fetched data to my state.
}
})
}
useEffect(() => {
preload(match.params.id);
// eslint-disable-next-line
}, []);
return (
<div>
<h1>Please use values fetched here.</h1>
</div>
);
}