Aug 27, 2024
localhost:2001 for demonstrationAppuseEffect hook for fetching data when the component mountscomponentDidMountfetchDatafetch API to request data:
resultresult.json()setAuthorsfetchData inside useEffectuseEffect(() => {
const fetchData = async () => {
const result = await fetch('http://localhost:2001/authors');
const json = await result.json();
setAuthors(json);
};
fetchData();
}, []);
avatar_urlUser 4fetch to POST data:
result.json() to process the responseconst addAuthor = async () => {
const newAuthor = { avatar: 'avatar_url', full: 'User 5' };
const result = await fetch('http://localhost:2001/authors', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newAuthor),
});
const json = await result.json();
setAuthors(prevAuthors => [...prevAuthors, json]);
};