Search code examples
reactjsreact-context

React Context Error When Consuming Multiple Context Value


I am getting error while consuming multiple react contexts. But my instructor had the same code that I am learning from youtube.

import React from "react";
import { UserContext, ChannelContext} 
from "../../App";

const E = () => {
return <div>
<p>How to consume multiple contexts</p>
<UserContext.Consumer>
    {user =>{
            return (
                <ChannelContext.Consumer>
                    {channel =>{
                            return (<div>
                User Context value {user} and {channel}
            </div>)
                        }
                    }
                </ChannelContext.Consumer>
            )
        }
    }
</UserContext.Consumer>
<p>First step is to create context</p>
<p>Second step is to wrap by provider</p>
<p>third step is to consume</p>
</div>;
};

export default E;

Solution

  • I have done a simple mistake of not writting Provider for one of the context.

    I have written

    <UserContext.Provider value={"Vishwas"}>
      <ChannelContext value={"codevolution"}>
        <C/>
        </ChannelContext>
      </UserContext.Provider>
    

    then I changed it to

    <UserContext.Provider value={"Vishwas"}>
      <ChannelContext.Provider value={"codevolution"}>
        <C/>
        </ChannelContext.Provider>
      </UserContext.Provider>
    

    Now It is working fine :)