Search code examples
reactjsreact-nativereact-reduxreact-hooksreact-context

How to pass a Array through Context native


Hi Dear thank you for turning in to my question , I am trying pass a array from one component to another using react-native context below is my try but it is not working for arrays

import React from 'react';


var context = {
    playlist: null, //like I want to make this value a array
    setPlaylist: (songID: string) => {

    }
}

export var playlistContext = React.createContext(context);

My App.tsx file

const [playlist, setPlaylist] = useState<string | null>(null);

<playlistContext.Provider value={{
    playlist,
    setPlaylist: (songID: string) => setPlaylist(songID),
}}>
    <Navigation colorScheme={colorScheme} />
    <StatusBar />
    <PlayerWidget />
</playlistContext.Provider>

Solution

  • Here is the answer by reforming the the playlistContext.tsx context API like below:

    import React from 'react';
    
    
    var context = {
        playlist: [],
        setPlaylist: (songID: string[]) => {
    
        }
    
    }
    
    export var playlistContext = React.createContext(context);
    

    Then I did this in my App.tsx so has to consume it in the provider

    const [playlist, setPlaylist] = useState<string | string[]>([]);
     <playlistContext.Provider value={{
                        playlist,
                        setPlaylist: (songID: string[]) => setPlaylist(songID),
    
                      }}>
    
                        <Navigation colorScheme={colorScheme} />
                        <StatusBar />
                        <PlayerWidget />
                      </playlistContext.Provider>