2

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.

0

1 Answer 1

8

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'))
Sign up to request clarification or add additional context in comments.

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.