Search code examples
reactjstypescripttslint

React .map an object


I've got an eslint error Property 'date' does not exist on type 'never', and it's on data.date. Any idea how can I fix it?

import React from 'react'
import app from './../Flamelink'

function App() {
  const [data, setData] = React.useState([])
  React.useEffect(() => {
    const fetchData = async () => {
      const data = await app.content.get({
        schemaKey: 'persons'
      })
      setData(data)
    }
    fetchData()
  }, [])
  return (
    <ul>
      {data.map(data => (
        <li>{data.date}</li>
      ))}
    </ul>
  )
}

export default App

Solution

  • First of all, I would use a different variable name instead of just calling everything data. This way you avoid variable shadowing errors.

    If you want your state variable to be data then call the answer you get from your fetch something else, result maybe. Then, when mapping your data state, call the current value something else too, maybe item or dataItem.

    Second, since you appear to be using TypeScript, you need to tell TS the structure of your data state array.

    Try this:

    function App() {
      const [data, setData] = React.useState<Array<{date: string}>>([]);
      React.useEffect(() => {
        const fetchData = async () => {
          const result = await app.content.get({
            schemaKey: "persons"
          });
          setData(result);
        };
        fetchData();
      }, []);
    
      return (
        <ul>
          {data.map(item=> (
            <li>
              {item.date}
            </li>
          ))}
        </ul>
      );
    }