Trying to change my data during a .map call

Viewed 44

During a .map from an array of data, I have another array of data, which I need to do a .map inside it too. It's looking a bit like this

First Data load

async function handleSubmit(event: FormEvent){
    event.preventDefault();
    await api.get(`people/?search=${input}`).then(response =>{
        setCharacters(response.data.results)
    })
}

Second Data Load

   async function getFilmName(film: string) {
        const movie = film.split("/");
        await api.get(`films/${movie[5]}`).then(response =>{
           return(response.data.title)
        })
  }

and then, the .map's

 {characters.map(characters =>{
            return (
                <div>
                    <Link to={`character/${characters.url.split("/")[5]}`}>{characters.name}</Link>
                    {characters.films.map((films) =>{
                        return(
                            <h5>{getFilmName(films)}</h5>
                        )
                    })}
                </div>
            )
        })}

and, in the end I receive a

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
2 Answers

getFilmName is Promise object. So It can't get file name in JSX context. So you need to use it in useEffect or other event handler and you need to save data in state. And you can render with right data.

And in that case, you can make some new component like,

function FileName ({file}){
  const [fileName,setFileName] = useState("")
  const getFileName = useCallback(async ()=> {...},[file])
  useEffect(()=>{
      getFileName()
  },[getFileName])
  return (<h5>{fileName}</h5>)
}

I think you ware using same variable name here

 {characters.map(character =>{
            return (
                <div>
                    <Link to={`character/${character.url.split("/")[5]}`}>{character.name}</Link>
                    {character.films.map((films) =>{
                        return(
                            <h5>{getFilmName(films)}</h5>
                        )
                    })}
                </div>
            )
        })}
Related