I am new to React and I get the Objects are not valid as a React child (found: object with keys {id, description, status, priority, created, deadline, emp}). If you meant to render a collection of children, use an array instead.
error and followed Link to solve the issue.
Upon running the object with the map
function I get the null error. Upon passing the object JSON.stringify()
I get the string ensuring data is returned by the API.
This is my data.
[ { "id": 1, "description": "asfd", "status": "ass", "priority": "p", "created": "2022-08-21", "deadline": "2022-07-28", "emp": 1 } ]
This is my code.
import React, { useState, useEffect } from 'react' const TaskPage = ({match}) => { let taskId = match.params.id let [task, setTask] = useState(null) useEffect(() => { getTask() }, [taskId]) let getTask = async () => { if (taskId === 'new') return let response = await fetch(`/task/task/${taskId}/`) let data = await response.json() setTask(data) } return ( <div> {task.map(task => <div>{task.id}</div>)} <div>{JSON.stringify(task)}</div> </div> ); }
What have I done wrong?
Advertisement
Answer
import React, { useState, useEffect } from 'react' const TaskPage = ({match}) => { let taskId = match.params.id let [task, setTask] = useState([]) useEffect(() => { getTask() }, [taskId]) let getTask = async () => { if (taskId === 'new') return let response = await fetch(`/task/task/${taskId}/`) let data = await response.json() setTask(data) } return ( <div> {task.length && task.map(task => <div>{task.id}</div>)} <div>{JSON.stringify(task)}</div> </div> ); }