[FIXED] Uncaught Error: Objects are not valid as a React child (found: object with keys {key, libelle}) : on a fetch API

Issue

I try to add my API and fetch the name of the town in it to put it in a my option on my select tag. but I'm not able to understand the mistake and correct it.

import React, {useState} from 'react';
import {Navigate} from 'react-router-dom'
import Entete from './MEP/entete'

function Localisation() {
  const [CP, setCP]= React.useState('');
  const [city, setCity]= React.useState('');
  const [ListVille, setList]= React.useState([]);
  const [goToExploit, setGoToExploit] = useState(false)

  function handleSubmit(event) {
    event.preventDefault()
    setGoToExploit(true)
  }

  if(goToExploit) {
      return <Navigate push to={`/exploitation`} />
  }

  function handleChange(event) {
    const CP = event.target.value
    setCP(CP)
    fetch('http://localhost:3000/api/1.0/getCommunes/' + CP ).then(function(response) {
        return response.json()
      }).then(function(response){
        setList(response)
        console.log(response)
      })
      console.log(ListVille)
 }

  return (
    <div>
      <Entete titre="Localisation"/>

      <form onSubmit={handleSubmit}>
        <div className='titre'> Saisissez votre code postal </div>
        <input 
        className='input'
        value={CP}
        onChange={handleChange}
        placeholder='Code Postal'
        type='text'
        required/>
        <div className='titre'> Saisissez votre ville {ListVille}</div>
        <select >
          <option value="">Choisissez</option>
          { Array.isArray(ListVille) ? ListVille.map((item)=>( <option value={item.key} > {item.libelle} </option> ) ) : ListVille===undefined ?  <option value={'pas de ville'}>  </option>  : <option value={ListVille.key}> {ListVille.libelle} </option> }
        </select>
        <div className='centrer'>
          <button type='submit' className='validation'> Valider </button>
        </div>
      </form>
    </div>
  );
}

export default Localisation;

When the CP is not a value of the API the select render only "choisissez" else it render the list of the town

When I enter a good CP the first console.log(response) render :

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {key: '41026', libelle: 'Brévainville'}
1: {key: '41028', libelle: 'Busloup'}
2: {key: '41073', libelle: 'Danzé'}
3: {key: '41095', libelle: 'Fréteval'}
4: {key: '41115', libelle: 'Lignières'}
5: {key: '41141', libelle: 'Moisy'}
6: {key: '41154', libelle: 'Morée'}
7: {key: '41172', libelle: 'Ouzouer-le-Doyen'}
8: {key: '41173', libelle: 'Beauce la Romaine'}
9: {key: '41186', libelle: 'Rahart'}
10: {key: '41214', libelle: 'Saint-Hilaire-la-Gravelle'}
11: {key: '41216', libelle: 'Saint-Jean-Froidmentel'}
12: {key: '41275', libelle: 'La Ville-aux-Clercs'}
length: 13
[[Prototype]]: Array(0)

and the second console.log(ListVille) render []

The all with the error message :

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

I tried :

  • put the fetch function in a UseEffect but it doesn't work neither
  • put a key in option like : <option key={item.key} value={item.key} > {item.libelle} </option>

Can someone help me or guide my to something ?

EDIT the seems to come from the ListVille const because when I tried this in mys render <div className='paragraphe'> Test {CP==='41160' ? ListVille[0].key : 'coucou'}</div> I've git the error message :

Uncaught TypeError: Cannot read properties of undefined (reading 'key')

EDIT 2 the problem seems to come from the fact that setList(response) doesn't set data in ListVille but I can't figure out why

EDIT 3 setList(response) does set data in ListVille but its's asynchronous so I need to force the setList to apply before doing anything else


Solution

After a lot of research I found where the problem was and I ask a more precise question about my problem in here other react question And the probleme was solved. Thanks everyone



Answered By - Aliénor
Answer Checked By - Pedro (Python.Easybugfix Volunteer)

Related Posts

Post a Comment