Home > database >  Received error 'objects are not valid as a React child' while mapping an array
Received error 'objects are not valid as a React child' while mapping an array

Time:08-28

Errors: -

Uncaught Error: Objects are not valid as a React child (found: object with keys {0}). If you meant to render a collection of children, use an array instead.
Uncaught Error: Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43}). If you meant to render a collection of children, use an array instead.

Code

import React from 'react';
import axios from 'axios';

export default class Cou extends React.Component {
  state = {
    Api1: [],
    Api2: [],
    Api3: [],
    Api4:[],
    currentTask:"",
  }

  componentDidMount() { 
    axios.get("https://assessment.api.vweb.app/users")
    .then(res => { const Api1 = res.data; this.setState({ Api1 }); }) 
    axios.get("https://assessment.api.vweb.app/products")
    .then(res => { const Api2 = res.data; this.setState({ Api2}); })
    axios.get("https://assessment.api.vweb.app/orders")
    .then(res => { const Api3 = res.data.map(item => ({...item, user_name: this.state.Api1.find(({user_id}) => user_id === item.user_id)?.name || "", product_name: this.state.Api2.find(({product_id}) => product_id === item.product_id)?.name|| "",})); this.setState({ Api3 }); })
  }

  handleChange = (e) =>
  {
    console.log(e.target.value);
    this.setState({
      currentTask:e.target.value,
    });
  };
  
  show = () =>{
    let cn = this.state.Api1.filter(m=>{return m.user_id == `${this.state.currentTask}`}).map(o=>{return((o.name))})
    let cd = this.state.Api3.filter(person => { return person.user_id == `${this.state.currentTask}`}).map(n => {return (n.product_name)})
    this.setState({
      Api4:[{coustomer_name: {...cn}}, {coustomer_detail:{...cd}}]
    })
  }
  
  render() {
    return (
      <>
        <div>
          <input type ="text" onChange={this.handleChange}/>
          <button onClick={this.show}> Show history</button>
          {this.state.Api4.map(p=>{return (<p>{p.coustomer_name} {console.log(p.coustomer_name)} bought,</p>)})}
          {this.state.Api4.map(p=>{return (<p>{p.coustomer_detail} {console.log(p.coustomer_detail)}</p>)})}
        </div>
      </>)
  }
}

3.Console log of api4 arr enter image description here

How to solve these errors. Here i am trying to print the data from array Api4 but the above errors are coming.

The problem is in printing the data from the array Api4. In show function i took value of cn and cd and put in array Api 4. Then while mapping the values from Api4 i got these errors.(The error is related to either in the way of storing values of cn and cd in Api4 or in mapping of Api4 for print).

CodePudding user response:

The issue is with this line:

Api4:[{coustomer_name: {...cn}}, {coustomer_detail:{...cd}}]

which converts the output cd array again into an object where keys are just the array indexes.

And you should use find instead of filter to find the customer name.

You can actually simplify the whole code like this:

import React from "react";
import axios from "axios";

export default class Cou extends React.Component {
  state = {
    Api1: [],
    Api2: [],
    Api3: [],
    Api4: [],
    currentTask: ""
  };

  componentDidMount() {
    axios.get("https://assessment.api.vweb.app/users").then((res) => {
      const Api1 = res.data;
      this.setState({ Api1 });
    });
    axios.get("https://assessment.api.vweb.app/products").then((res) => {
      const Api2 = res.data;
      this.setState({ Api2 });
    });
    axios.get("https://assessment.api.vweb.app/orders").then((res) => {
      const Api3 = res.data.map((item) => ({
        ...item,
        user_name:
          this.state.Api1.find(({ user_id }) => user_id === item.user_id)
            ?.name || "",
        product_name:
          this.state.Api2.find(
            ({ product_id }) => product_id === item.product_id
          )?.name || ""
      }));
      this.setState({ Api3 });
    });
  }

  handleChange = (e) => {
    console.log(e.target.value);
    this.setState({
      currentTask: e.target.value
    });
  };

  show = () => {
    let cn = this.state.Api1.find((m) => {
      return m.user_id == `${this.state.currentTask}`;
    })?.name;
    let cd = this.state.Api3.filter((person) => {
      return person.user_id == `${this.state.currentTask}`;
    }).map((n) => {
      return n.product_name;
    });

    this.setState({
      Api4: { coustomer_name: cn, coustomer_detail: cd }
    });
  };

  render() {
    return (
      <>
        <div>
          <input type="text" onChange={this.handleChange} />
          <button onClick={this.show}> Show history</button>
          <br />
          {this.state.Api4?.coustomer_name && (
            <>
              <h2>{`${this.state.Api4?.coustomer_name} bought,`}</h2>
              {this.state.Api4?.coustomer_detail?.map((p) => {
                return <p>{p}</p>;
              })}
            </>
          )}
        </div>
      </>
    );
  }
}

Working Demo

Edit vigilant-voice-hkzt15

CodePudding user response:

In your function show you assig to Api4 properties Api4:[{coustomer_name: {...cn}}, {coustomer_detail:{...cd}}] they are objects. As React said to you, you can't use object as React.Child. You should handle object for instance cast it to array with Object.values(cn) and React will render your array of names (without comma).

And then you can loop through your array and style it like so: coustomer_name.map(name => <div>{name}</div>)

CodePudding user response:

I believe that you are getting that error because you are trying to map the response object that you received from the request. Try to first extract the data into an array and then pass it to Api4

CodePudding user response:

Isn't it what you are trying to do ?

    show = () =>{
  const cn = this.state.Api1.find(m => m.user_id == `${this.state.currentTask}`)?.name || ""
  const cd = this.state.Api3.find(m => m.user_id == `${this.state.currentTask}`)?.product_name || ""
  this.setState({
    Api4:[{coustomer_name: cn}, {coustomer_detail: cd}]
  })
}

CodePudding user response:

Try this code :

import React from 'react';
import axios from 'axios';

export default class Cou extends React.Component {
    state = {
        Api1: [],
        Api2: [],
        Api3: [],
        Api4: [],
        currentTask: "",
    }

    componentDidMount() {
        axios.get("https://assessment.api.vweb.app/users")
            .then(res => { const Api1 = res.data; this.setState({ Api1 }); })
        axios.get("https://assessment.api.vweb.app/products")
            .then(res => { const Api2 = res.data; this.setState({ Api2 }); })
        axios.get("https://assessment.api.vweb.app/orders")
            .then(res => { const Api3 = res.data.map(item => ({ ...item, user_name: this.state.Api1.find(({ user_id }) => user_id === item.user_id)?.name || "", product_name: this.state.Api2.find(({ product_id }) => product_id === item.product_id)?.name || "", })); this.setState({ Api3 }); })
    }

    handleChange = (e) => {
        console.log(e.target.value);
        this.setState({
            currentTask: e.target.value,
        });
    };

    show = () => {
        let cn = this.state.Api1.filter(m => { return m.user_id == `${this.state.currentTask}` }).map(o => { return ((o.name)) })
        let cd = this.state.Api3.filter(person => { return person.user_id == `${this.state.currentTask}` }).map(n => { return (n.product_name) })
        var api4 = []
        for (var i = 0; i < cn.length; i  ) {
            api4.push({ 'coustomer_name': cn[i], 'coustomer_detail': cd[i] })
        }
        this.setState({
            Api4: api4
        })
    }

    render() {
        return (
            <>
                <div>
                    <input type="text" onChange={this.handleChange} />
                    <button onClick={this.show}> Show history</button>
                    {this.state.Api4.map(p => { return (<p>{p.coustomer_name} bought,</p>) })}
                    {this.state.Api4.map(p => { return (<p>{p.coustomer_detail}</p>) })}
                </div>
            </>)
    }

}
  • Related