API retruns [object Object]

Viewed 63

I am trying to get the body of my api request in reactJS. It returns the right 'body' on the submitHandler function but returns [object Object] when called on a different component. Below is my code:

Login (SubmitHandler):

 submitHandler(event) {
        event.preventDefault()
     
        axios
            .post("http://localhost:8000/rest-auth/login/", this.state)
            .then(res => {
                 if (res.data){
                    sessionStorage.setItem('data', res)
                    this.setState({redirect:true})
                }
                console.log(res.data)
            })
            .catch(err => {
                this.setState({
                    error: true, errorMessage: err
                })
                // console.log(this.state.errorMessage)
            })
    }

profile(componentDidMount):

 componentDidMount()
    {
        if(sessionStorage.getItem('data')){
         let  user_data = sessionStorage.getItem('data')
            console.log(user_data)
        }
        else {
            this.setState({
                redirect:true
            })
        }
}

componentDidMount returns [object Object] instead of an api body response.

1 Answers

This isn't about the API, this is about the sessionStorage you're using.

You can only store stringsin local storage or session storage; the setItem API will implicitly call .toString() on anything you pass in, which for objects results in [object Object].

You'll want to encode the content to e.g. JSON, that is

sessionStorage.setItem('data', JSON.stringify(res.data))

and decode it on load,

let user_data = JSON.parse(sessionStorage.getItem('data'))
Related