score:0
There are a few conceptual misunderstandings that I want to tackle in your code.
In modern React, your components should typically render some type of jsx, which is how React renders html. In your first example, you are using App to return your genres to your Screen component, which you don't need to do.
If your goal is to fetch some genres and then ultimately print them out onto the screen, you only need one component. Inside that component, you will useEffect to call an asynchronous function that will then await the api data and set it to a react state. That state will then be what you can iterate through.
When genres is first rendered by react on line 6, it will be undefined. Then, once the api data is retrieved, React will update the value of genre to be your array of genres which will cause the component to be re-rendered.
{genres && genres.map((genre)
... on line 20 checks to see if genres is defined, and only if it is, will it map (like looping) through the genres. At first, since genres is undefined, nothing will print and no errors will be thrown. After the genres are set in our useEffect hook, genres will now be an array and we can therefore loop through them.
Here is a working example of your code.
import React, { useState, useEffect } from "react";
import { getGenres } from "./api/functions";
function App() {
const [genres, setGenres] = useState();
useEffect(() => {
async function apiCall() {
const apiResponse = await getGenres("tv");
console.log(apiResponse);
setGenres(apiResponse);
}
apiCall();
}, []);
return (
<div>
<h1 className="text-3xl font-bold underline">H1</h1>
{genres && genres.map((genre) => <div key={genre}>{genre}</div>)}
</div>
);
}
export default App;
score:0
You should use a combination or useEffect
and useState
You should use useEffect
to launch the async get, without launching it each rerendering. If a async function is used to get some data from outside the component, this is called 'side effect' so use useEffect
.
You should use useState
to react to changes on theses side effects, re-rendering the component to get the data in the dom.
In the next example, Im using a dummy async function getGenres
which returns an array of genres.
Here is an example and a WORKING EXAMPLE :
const {useState, useEffect} = React;
async function getGenres() {
var promise = new Promise(function(resolve, reject) {
window.setTimeout(function() {
resolve( ['genre1', 'genre2']);
});
});
return promise;
}
const Screen = () => {
const [genres, setGenres] = useState([])
useEffect(
() => {
getGenres().then(
res => setGenres(res)
)
}, [getGenres]
)
return (
<ul>
{
genres.map(
i => <li>{i}</li>
)
}
</ul>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<Screen/>)
Source: stackoverflow.com
Related Query
- How to use data of an Async function inside a functional component to render HTML in React
- How to use useState inside a react functional component which is async
- use of variable inside render function of react component
- How to not use setState inside render function in React
- How to use React Context inside function of Class component
- How to use Render Props in functional component using typescript
- How to use Bootstrap Modal inside map function in React Js to render indivisual elements?
- How to render react component inside function in another component?
- How to test a function inside React functional component using jest.spyOn with React Testing Library
- How to test functional component with async callback inside useEffect using snapshots
- How to Use componentDidMount() in Functional Component to execute a function
- how to use async function with custom hooks inside useEffects
- How to access useEffect's async data in another function within a component in React
- How to use async javascript inside react render
- how to use one component render many html fragment in reactjs?
- How to use a typed selector inside of a nested function within a React Functional Component?
- How to conditional render inside map in a functional component of react js
- How could I use a class component inside function component
- How to use setState inside render function without onClick event
- How to use Switch case in React js functional component inside return efficiently by reusing?
- How to pass data from a parent component or use axios here in the map function for react-google-maps library?
- How to put data inside a customize state in for loop in functional component
- How do I convert this function into a class component so that I can use render to call the return?
- How can i pass HTML inside React Hook Function and display inside my component secure?
- React, How to send props from parent component to child component? (to use those props outside render function )
- How to set HTML data attributes inside render in React?
- How to use data from a callback function in the render method in a react class
- How to use children with React Stateless Functional Component in TypeScript?
- How to Call a Function inside a Render in React/Jsx
- How to call an async function inside a UseEffect() in React?
More Query from same tag
- React - how to wait and fade out?
- Checkbox/Radio onChange event not returning the standard event object (Only if React-plus-Carbon)
- Can the default value of a Recoil atom be an object?
- how to make clickable part of <tr> in next js?
- What is the right way to assign element of an array to state using React hooks?
- How to pass a variable inside a component in react
- How do you center a div element in react w/out external css file
- How to setup Cloudfront & S3 to point to index.html for every route?
- ReactJS, onScroll doesn't work for dynamic navbar
- How to register event with useEffect hooks?
- component is not rendered when getting data from localStorage in an event handler
- Spying on React functional component method with jest and enzyme; Cannot spyOn on a primitive value
- How to change the style of a single component within an other component with styled-components?
- React Navigation Header change with screen
- react-router-dom nested routes and redirects
- How to change state value when checkbox change using ReactJS
- Get SVG from react-icons components
- Cancel old Promise.resolve if same method called multiple times with given timeframe
- Typescript addEventListener to keydown giving error
- React css precedence
- Making Browserify bundle play nice with ReactDevTools
- How do I disable onMouseEnter/onMouseLeave events based on screen width?
- How to fetch data in ReactJS from NodeJS API for Influxdb?
- Reading environment variable in run time after running npm build for a create-react-app based project
- React.js: Get values as string from a state array
- Pushing to array in React
- Is it possible to share states between components using the useState() hook in React?
- How to connect NodeJS with ReactJS front-end
- Cannot find module 'has-flag'
- Toggle showing and hiding components in ReactJs