0

How can I save my object that is fetched from API in state in such a way that after page refresh it should be still available.How to save fetched data from API to state with parameter name?

As i don't want to save object in local storage or session storage.

This can be helpful in such a way that before fetching to the same API it will check if the object is already there then no fetching is required for that API

Suppose mine API look like https://example.com/new/${numberID}/staff

When first time API is executed for the {numberID} => 12ab1 parameter it should store the result for that {numberID} in state now when {numberID}=> 13ab2 parameter is updated again it should store in new state in such a way

Now {numberID} => 12ab1 parameter called again rather fetching from API it should fetch details from state. this will save my API re- hitting

Is this possible using react-hooks?

1
  • data stored in the state is set to blank or default value you set after each refresh Commented May 3, 2020 at 11:21

2 Answers 2

2

This is not possible.

State is maintained for the lifetime of the application. When you refresh the page, you are destroying the current instance of the application and creating a new one, therefore state can not be persisted.

The only way to persist data across a refresh is to use third party software or things like browser storage.

Sign up to request clarification or add additional context in comments.

Comments

0

Use localStorage API https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

You can put your data in localStorage and get it from there if you need it. For example

          if (!localStorage.getItem('data')) {
              axios.get(`https://example.com/new/${numberID}/staff`)
                  dispatch({
                      type: "FETCHSUCCESS",
                      payload: response.data
                  });
                  localStorage.setItem('data', response.data);
              })
              .catch(error => {
                  dispatch({
                      type: "FETCHFAILURE"
                  });
              });
          }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.