I am currently learning React.
After reading the docs and trying some examples, I still couldn't figure out how to make this code work:
Issue:
View not re-rendering after data fetched/state changed.
The application loads an initially mocked data and then fetches the real data from the server, but despite fetching it correctly the view doesn't re-render as expected when using setCdp
.
Some points to consider:
- All objects are correctly defined. Mock data renders correctly, no errors on the App.
- All data is correctly arriving from the server.
console.log()
returns all the expected data.
Expected behavior:
The view should be updated and re-rendered with the newly fetched data, replacing the old data with the new one.
Code:
// Mock data declaration omitted...export default function App() { const [cdp, setCdp] = useState(cardapio); useEffect(() => { fetch('https://ec*****.com.br/frontcontroller.php?file=getpratos.php') .then(res => res.json()) .then((newState: Cardapio) => { setCdp({...newState}); // Doesn't seem to be working. Passing deep clone. console.log(newState); // Data is logged as expected. }) }, []) return (<View style={styles.container}><CardapioPage cardapio={cdp}/><StatusBar style="auto"/></View> );}// StyleSheet "styles" also omitted.
CardapioPage
type Props = { cardapio: Cardapio};export const CardapioPage = (props: Props) => { const [cardapio, setCardapio] = useState(props.cardapio); return (<View><CardapioView cardapio={cardapio}/></View> );};