Objects are not valid as a React child (found: object with keys {job}). If you meant to render a collection of children, use an array instead

Viewed 894

Using axios to fetch data from an api and then trying to map the values and display them in a different component.

App.tsx

import React, { useState, useEffect } from 'react';
import JobBoardComponent from './components/JobBoardComponent';
import axios from 'axios';

function App(): JSX.Element {

  const[jobs, setJobs] = useState<any>([]); 

  useEffect((): void => {
     const fetchJobs = async () => {
        const res = await axios('http://localhost:5000/jobs');
        setJobs(res.data);
     };
     fetchJobs();
  }, []);

  
  return (
    <div className="App">
     {jobs.map((job: any) => <JobBoardComponent job={job} key={job.id} />)}
    </div>
  );
}

export default App;


JobBoardComponent.tsx

import React from 'react'

function JobBoardComponent( job: any, key: any){
    return (
        <div>
           <h1>{ job }</h1>
        </div>
    )
}

export default JobBoardComponent;

It looks like the API is working.

I am following this tutorial https://www.youtube.com/watch?v=JZQ8m08cbF0 but I decided to make my own API and now it doesn't work.

1 Answers

Please, do not use any unless you are in the process of migrating a js project to ts (or you REALLY don't care what type the variable will be, even then you still should consider using unknown type instead.)

As for your problem, if I were you, for the quick and dirty way of displaying the "unknown" data I would do something like this (or just console.log it if data is too large):

    ...
    <h1>{ JSON.stringify(job) }</h1>
    ...

And I am guessing, from the error you just mentioned (and from the above script that will justify my guess if you include it), job is a nested object, which is not valid data for displaying in React. Probably you should destructure your job variable inside JobBoardComponent.

Again, you can avoid these kind of errors if you give your job variable a non-any type, linter will warn you if you are assigning wrong types, which you can't when using any.

Related