so I'm building a react and node project
as a part of it, I do a fetch call and I console.log the response
import React, { useState, useEffect } from 'react';
import Downshift from 'downshift'
export default function TestSearchBar() {
const [pokemonData, setPokemonData] = useState(null);
useEffect(() => {
Pokemons();
async function Pokemons() {
const res = await fetch(
`http://localhost:3001/pokemon/names`
);
const data = await res.json();
setPokemonData(data);
}
}, []);
const items = pokemonData;
return (
<div>
<Downshift
onChange={selection =>
fetch(`http://localhost:3001/search/${selection.value}`).then(res => res.json()).then(data => console.log(data))
}
itemToString={item => (item ? item.value : '')}
>
{({
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
isOpen,
inputValue,
highlightedIndex,
selectedItem,
getRootProps,
}) => (
<div>
<label {...getLabelProps()}>Enter a pokemon </label>
<div
style={{ display: 'inline-block' }}
{...getRootProps({}, { suppressRefError: true })}
>
<input {...getInputProps()} />
</div>
<ul {...getMenuProps()}>
{isOpen
? items
.filter(item => !inputValue || item.value.includes(inputValue))
.map((item, index) => (
<li
{...getItemProps({
key: item.value,
index,
item,
style: {
backgroundColor:
highlightedIndex === index ? 'lightgray' : 'white',
fontWeight: selectedItem === item ? 'bold' : 'normal',
},
})}
>
{item.value}
</li>
))
: null}
</ul>
<p></p>
</div>
)}
</Downshift>,
</div>
);
}
I want to insert the data that goes into the console into jsx and have it return something like
<div>
pokemon name {data.name}
pokemon stats {data.stats}
</div>
I can't figure out how to share the data I fetched and put it into the console to be put into the jsx tnx
CodePudding user response:
Move the fetch logic into another effect with dependency on a selection value. So when selection will change pokemon will be refetched. Then print to console and update a state of the component. Like this:
const [selection, setSelection] = useState();
const [pokemon, setPokemon] = useState();
useEffect(() => {
const fetchPokemon = async () => {
const pokemon = await ...
console.log(pokemon);
setPokemon(pokemon);
}
if (selection) {
fetchPokemon();
}
}, [selection])
<Downshift onChange={selection => setSelection(selection.value)} ...
{pokemon && <div>
pokemon name {pokemon.name}
pokemon stats {pokemon.stats}
</div>}
CodePudding user response:
The first thing I notice is your dependency array in your useEffect is empty, and you are updating state in it. This causes an infinite render loop which could be why you are not seeing anything on the screen.
useEffect(() => {
Pokemons();
async function Pokemons() {
const res = await fetch(
`http://localhost:3001/pokemon/names`
);
const data = await res.json();
setPokemonData(data);
}
// Change here:
}, [pokemonData]);