I am trying to figure out how I can pass the JSON object returned from my server to the react hook to update a state, but I am coming across an error stating that objects are not valid. Does this mean that I would have to pass this as an array or a string? I tried googling around, but couldn't find a straightforward answer.
Here is my error message:
Error: Objects are not valid as a React child (found: object with keys {status, body}). If you meant to render a collection of children, use an array instead.
Here is what the JSON looks like:
{
message: {
body: "User does not exist in the database.",
status: "error"
},
user: {
authenticated: false,
user_id: "",
user_email: ""
}
}
Here is my code:
import axios from 'axios';
import React, { useContext, useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { SessionContext } from '../../../contexts/AppSession'
const SignInForm = () => {
const [{ email, password }, setForm] = useState({ email: null, password: null })
const [message, setMessage] = useState()
const { user, setUser } = useContext(SessionContext) // here you are calling a hook at component body
const router = useRouter()
const signIn = (e) => {
e.preventDefault();
axios.post('/api/auth/signin/', { email, password }, {
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then((res) => {
const data = res.data;
// Set user session state with returned user data
setUser(data.user)
// Set the message
setMessage(data.message)
}).then(()=> {
// On successful sigin, redirect to /app/profile/
if (message.status !== 'error'){
router.push('/app/profile/')
}
}).catch((err) => {
console.log(err)
console.log(err.request)
console.log(err.message)
})
}
useEffect(() => {
console.log(user)
}, [user]) // with that console.log will run on every user change
return (
...
)
}
export default SignInForm;