简体   繁体   中英

React : Hook doesn't get new data

I'm fetching data using axios in React .

const [ListProfil, setListProfil] = React.useState([]);  

useEffect(() => {
    axios
        .get("http://localhost:8000/api/profile/selected/10")
        .then((response) => setTimeout(()=>{
            setListProfil(response.data.data);
            console.log(response);
        }, 0))
        .catch((err) => console.log(err));
}, []);

The array that is returned have two elements:

在此处输入图像描述

Now when I'm adding a new element with onAdd , the axios request to POST is executed without problem. And after sending the POST request I'm sending a second request GET to retrieve the new data directly from database.

 const onAdd = (e) => {
        e.preventDefault();

        const infos = {
            username: username,
            user_id: 10,
            p_color: "#ffffff",
            country: "ma",
            address: "zezefez",
        };

        console.log(infos);

        axios
            .post("http://localhost:8000/api/profile/", infos)
            .then((res) => {
                toast(
                    <div class="text-primary font-weight-bolder">
                        Social link added successfully!
                    </div>,
                    { delay: 0 }
                );
                console.log(res);
            })
            .catch((error) => {
                console.log(error);
            });
            
        axios
            .get("http://localhost:8000/api/profile/selected/10")
            .then((response) => setTimeout(()=>{
                setListProfil(response.data.data);console.log(response);  console.log(ListProfil);
            }, 0))
            .catch((err) => console.log(err));     

    };

The problem here is when I get the data the second time, React doesn't set it in the hook as he did the first time.

Meaning that I'm getting the data from database correctly, but the array inside the hook that is supposed to receive the new data still have the old data. I tried setting a second different hook but it didn't work.

BUT surprisely it will receive the data AFTER I create a second element or refresh the page.

So I'm constantly having a delayed list inside the array of

const [ListProfil, setListProfil] = React.useState([]);

How can I have the new data from the database inside the hook?

In the following image:

1- The added element with username : testing_new_profile
2- The console.log(ListProfil) returning the final new array.
3- -----
4- The received data from database, note that there is the new element present because `Array(3)`.
5- The console.log(ListProfil) still returning the old array even after getting the new array from database.

在此处输入图像描述

after sending the POST request I'm sending a second request GET to retrieve the new data directly from database.

You are not actually doing this because the code runs asynchronously. What is actually happening is that both your POST and GET run at the same time, then the results come back in whatever order they come back in, triggering their respective then blocks.

If you want them to run sequentially you need to wait for the POST call to finish then you fire your GET call:

axios.post(...)
  .then(...)
  .then(() => {
    return axios.get(...).then(...)
  })
  .catch(...)

Here is a great article on promises I always recommend

For anyone interested this is how I solved it and retrieved the last element of the new list that I get with axios post :

    axios
        .get("http://localhost:8000/api/profile/selected/10")
        .then((response) => {
            setListProfil(response.data.data);          
    let newData= [response.data.data.slice(-1)[0]];
    let idData= newData[0];
    let ok = idData.id;

Seeing that I was getting the right data from the database but I was failing at storing it in the hooks, I created a new let newData where I will be receiving response.data.data directly AND at the same time added .slice(-1)[0] in the same line to get the last element of the list.

After that, the output of newData is a single array of the last element of the new list with an index of 0.

Now I should get the first and only array available with newData[0] and store it in idData .

And finally to get the id of that array idData.id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM