简体   繁体   中英

Where to save JSON response from api?

I'm new in react. Right now i'm working with axios . I'm getting back JSON file with data. I need to store it somewhere . Where I should store it? in localStorage or in state? Later I need to map it and display that data. What is the best and efficient way. Right now I'm storing It localStorage and in state. Than from state mapping it

getTemplates() {
    let token = localStorage.getItem("token")
    axios
      .get("http://dev.candidates.hrmessenger.com/stage/get-template", {
        mode: "cors",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization: `Bearer ${token}`,
        },
      })
      .then(res => {
        localStorage.setItem("data", JSON.stringify(res.data))
        this.setState({
         data:JSON.parse(localStorage('data'))
       })

      })
      .catch(error => {
        console.log(error)
      })
  }



this.state.data.map((item, index)=>{
return (
<div key={index}>{item}</div>
)
})

you should store the data in the state and call setState if you want to change the state data again, its the best way to get the data ie the response and set it in the State so you don't have to clear the local Storage. and local Storage is not a good practice

My suggestion is to use Redux and Redux-Persist . Redux-Persist Reference

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