简体   繁体   中英

(reactjs) how to set a promise or set the current state into local storage

I'm trying to build a very simple app for searching articles and using the localstorage to display more info about each article but when I set to save into the session storage for some reason is saving the initial or previous state, I assume because I need to set async for this but I just can't figure how

This is how I have it right now, findArticleQuery() is called on the handleSubmit

 useEffect(
      () =>{
          findArticlesQuery();
      } ,[]
  ) 
  const findArticlesQuery = (query) => {   //search function
    axios.get(`url`)
    .then(res => {                
      [res.data].map((val) =>(        
        setState(val)         
      ))                                     
    }).catch(error => {
      console.log(error.response)
    });        
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    findArticlesQuery(e.target.search.value)
    sessionStorage.setItem('localData', JSON.stringify(state))   //<--here I get the value of the previous state          
    e.target.search.value = '';       
  }

I need to use the session storage because I will have a detailed article component page.

Thank you guys!

You can get search result from findArticlesQuery() like below.

...
  const findArticlesQuery = (query) => {   //search function
    return axios.get(`url`)
    .then(res => {                        
      setState(res.data)
      return res.data
    })   
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    findArticlesQuery(e.target.search.value)
       .then(val => sessionStorage.setItem('localData', JSON.stringify(val)))
    e.target.search.value = '';       
  }

For saving state in the localStorage with React Hooks, something I've been using and that is extremely convenient is useLocalStorage .

Disclaimer : I am not the creator of this lib.

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