Home > Mobile >  React cannot read properties of null (reading 'map')
React cannot read properties of null (reading 'map')

Time:07-23

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?

CodePudding user response:

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>
  );

}

CodePudding user response:

You are fetching data which is an async operation. Before the data is loaded, the state is null. As the state is null, you can't map to a null element. Either you set the state to empty array like this.

let [task, setTask] = useState(null)

Or you can do this in return.

<div>

  {task && task.map(task => <div>{task.id}</div>)}
  <div>{JSON.stringify(task)}</div>
</div>

This will check if the task has some data and then it will use the map function.

CodePudding user response:

go through this link to see it

  • Related