soubhagya pradhan
soubhagya pradhan

Reputation: 547

How to log data after calling function

    class WorldMap extends React.Component { 
        constructor(props){
            super(props);
            this.state = {

            }
        }

            getGeography(){
              let url = FormatUrl(`/api/category/sov-geography/`)
              fetch(url)
              .then(res => res.json())
              .then(res => {
                localStorage.setItem("india", res['india'])
                localStorage.setItem("us", res['us'])
                localStorage.setItem("uk", res['uk'])
              })
            }



         customComponentDidMount(){
            this.getGeography()
            console.log(localStorage.getItem('us'))
         }
        }

Here i am fetching data from one api and storing the same data in localStorage() But when i am logging the data from localStorage() after calling this.getGeography() function i am getting null data.

I thing function is calling later . Is there any way to fix this.??

PLease have a look

Upvotes: 0

Views: 19

Answers (1)

ApplePearPerson
ApplePearPerson

Reputation: 4439

You can return the promise that fetch creates in the getGeography function like so:

getGeography() {
    let url = FormatUrl(`/api/category/sov-geography/`)

    return fetch(url)
        .then(res => res.json())
        .then(res => {
          localStorage.setItem("india", res['india'])
          localStorage.setItem("us", res['us'])
          localStorage.setItem("uk", res['uk'])
        });
}

This means getGeography will return a promise which you can .then like so:

customComponentDidMount() {
    this.getGeography().then(() => {
        console.log(localStorage.getItem('us'))
    });
}

Upvotes: 1

Related Questions