Home > database >  How to re-render a page by updating the state In React using functional component.?
How to re-render a page by updating the state In React using functional component.?

Time:10-01

I am dealing with POST and GET request. When user makes a POST request data gets stored in the DB. In GET request I am retrieving the data from DB.

In my useEffect I am using the GET request to get the data. It works only when page renders for the first time. It does not update the state whenever I make a POST request . I have to manually refresh the page to get the new data. When I put the state in my dependency it keeps making the fetch request as long as I am on that component . Below is my code..

Post Request

The post request is being made from child component.

 const  addFolder = async() => {
  if (!folderName) {
        alert("Folder Name Required");
    } else {
       const projectId = props.match.params.projectId
        console.log("Project Id ==> ",projectId)    //use projectId to make a call to the server..
        console.log(folderName)
       await fetch(`http://localhost:8080/mirFolder/new/${projectId}`,{
            method:"POST",
           body: JSON.stringify({
               "title":folderName,
           }),
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${token}`,
                 },
           }).then((res)=>{
            console.log(res)
            // window.location.reload()
            return res.json();            
        }).catch((err) =>{
            console.log(err)
        })
      }
     }

GET request function

const [state, setstate] = useState([]);

 useEffect(() => {
  const token = isAuthenticated().token;
  const projectId = props.match.params.projectId;
 
   getMirFolderbyProject(token, projectId).then((data) => {
    if (data.error) {
    console.log(data.error);
     } else {
      console.log("data ==>", data);
      setstate(data);
    }
    });
 }, []);

GET fetch Api

export const getMirFolderbyProject = (token, projectId) =>{
 return fetch(`http://localhost:8080/mirFolder/by/${projectId}`, {
  method: "GET",
  headers: {
   Accept: "application/json",
   "Content-Type": "application/json",
   Authorization: `Bearer ${token}`,
  },
  })
  .then((response) => {

 return response.json();
 })
   .catch((err) => {
   console.log(err);
  });

}

CodePudding user response:

This is because when a server gets a POST it will not serve new data, if you want the new data to be displayed after the POST request make sure to serve the new data to the client in the POST request.

CodePudding user response:

you should fill your dependencies array with the variables which on change you would want re-render the component

const [state, setstate] = useState([]);

 useEffect(() => {
  const token = isAuthenticated().token;
  const projectId = props.match.params.projectId;
 
   getMirFolderbyProject(token, projectId).then((data) => {
    if (data.error) {
    console.log(data.error);
     } else {
      console.log("data ==>", data);
      setstate(data);
    }
    });
 }, [token , projectId]);

CodePudding user response:

As @Klump said, when you made the POST request and update the data in DB, you again need to make a GET request instead of fetching updated data fetched from the POST response in order to keep the consistency.

For this, once the POST request promise resolved, you can use an additional fetching state in order to make a GET request.

Please provide your complete implementation containing both GET and POST requests with all the necessary components to further work on it.

  • Related