Home > Back-end >  How to initialize state variable such that get request is made on the current url?
How to initialize state variable such that get request is made on the current url?

Time:10-25

I am trying to generate url based on the params data

Here is the code:

const Feeds = () => {

 const [url, setUrl] = useState("");

 useEffect(() => {
        switch (params.category) {
            case "news_National":
                setUrl("http://localhost:8090/newsOnAir/national");
                break;

            case "news_International":
                setUrl("http://localhost:8090/newsOnAir/international");
                break;

             case "XYZ":
                navigate("/home");
                break;

            ...........
            ...........}

           axios.get(url)
            .then((response) => {
               console.log(response);
            })
            .catch((err) => {
                console.log(err);
            });

     },[params.category])



   return (........)
}

But the problem occurs when the get request is made to the previous URL state data. When a get request is made at that time the old data persists then the state is changed.

I cannot eliminate the use of useEffect since the switch case has navigate logic for some cases.

Please guide me on how to overcome this issue.

CodePudding user response:

There is really no need of using useEffect here. See Updating state based on props or state.

Define a function to calculate url

function getUrl(category) {
  // calculate url here based on params.category
}

// then simply use the url by calling function

const Feeds = () => {

  const url = getUrl(params.category)

  // ... rest of code

}

CodePudding user response:

React setState method is asynchronous, which means that even if you called your "setState" method, it will not ensure that your state is updated immediately.

To bypass this, you can either :

use setState callback, which ensures that your state has been updated, like this :

setUrl(url, () => {
    //url is now updated with the right value
});

or put your Api call inside an useEffect hook, where you check the value of url like this :

useEffect(() => {
   if (url !== "")
   {
      //Here your url should be OK
   }
}, [url])
  • Related