Home > database >  Passing an array of Object using Provider in React
Passing an array of Object using Provider in React

Time:12-22

I have fetched the following API from "https://api.github.com/users" and was trying to share the array via provider using react. How do I do this ?



function ApiData() {

    // Assign the Array and set it an empty array
    const [users, setUsers] = useState([]);
    const [loadDataState, setloadDataState] = useState(false) // Initates a loadData variable to set initial state as false

    const baseUrl = 'https://api.github.com/users'

    useEffect( () => {
        axios.get(baseUrl)
            .then((Response) => 
            {
                console.log('========== Github Api  ==========')
                setUsers(Response.data)
                console.log('Json Array', Response.data)
                console.log('User Array', users);
                console.log('=================================')
                setloadDataState(true);
            })
            .catch(error => {console.error(error)})
    }, []);
    
    return (
        <>
            <dataArray.Provider>
                
            </dataArray.Provider>
        </>
    )
}

export default ApiData  ```

CodePudding user response:

If you want to use state providers, I would sugget for you to use Redux (if you're working on a project with complexe states), if not you could use Contexte API for a simple logic.

CodePudding user response:

When you use react context Provider can have a value property which will receive the data which will be provide to all sub component which use the context.

<MyContext.Provider value={/* some value */}>

In case the value props isn't provide the value which will be provide to sub component is the value which was provide when you call React.createContext

const MyContext = React.createContext(defaultValue);
  • Related