0

I am developing an app using javaScriptServices, with the react+redux template. I am consuming an API endpoint that returns an image as base64, this image happens to be a user avatar image. Code for cosuming endpoint:

axios.post(API_URL+"api/sample/endpoint").then(function(response){
    saveAvatarLocalStorage(response.data.result);
}).catch(...)

function for saving to local storage:

function saveAvatarLocalStorage(data:any){
    localStorage.setItem('avatar',data);
}

When I get the image I save it to local storage, and then i consume it from different parts of my code, and avoid API calls.

Code for getting the base64 image from localstorage:

componentDidMount(){
    ....
    var imgB64 = userService.loadUserAvatar();
    this.setState({imgAvatar: imgB64});
}

and this is how i display the image:

<img src={this.state.imgAvatar}/>

So far, so (apparently) good. The big problem I am facing is that an image sizing 1 to 2 mb can be a really huge string to save in local storage, and since localstorage calls are asynchronous, some times my app loads all the data from the api, but the local storage image is not yet ready. Can some one help me on this?

  • This question needs an mcve - https://stackoverflow.com/help/mcve . Give us minimal code that demonstrates your issue, and someone is more likely to be able to tell you what's wrong. – slim Feb 06 '18 at 17:07
  • 1
    Why not save the base64 string in state rather than in local storage!! – Dev Feb 06 '18 at 17:16
  • ... and furthermore, store it un-base64'd in the Redux state. – slim Feb 06 '18 at 17:25
  • Hmm i have read about it... but what about when page reloads, won't this cause the state to be lost? – Oscar Cabrera Rodríguez Feb 06 '18 at 17:28
  • Bit confused what you mean by "since localstorage calls are asynchronous"--at least per [this previous question](https://stackoverflow.com/questions/20231163/is-html5-localstorage-asynchronous) it sounds like localStorage.getItem should be synchronous. – ecraig12345 Feb 07 '18 at 12:00
  • Well, it seems so... I haven't read about that, but my problem is that when i do localStorage.setItem("some","stuff"); I do not know when it finishes to save. I am evaluating [https://react-bootstrap.github.io/components/dropdowns/] localForage, that has similar functionality, and besides, it provides a callback to notice when opration ends – Oscar Cabrera Rodríguez Feb 07 '18 at 18:12

0 Answers0