Search code examples
reactjsstatesetstateuse-context

useContext - my parent does not render when i set state in the child


I am not that good at react js.. I just wanted to make a "Global value" to let the childs of that parent see that value so I found useContext that allow sharing values along. so I wanted to use (useState) so I can set it from the child so it can render alone in my parent but seems that isnt working .. its changing the value but not render it in the parent (how I figure that out .. while running, I changed the value and then removed the <Home video = {video}/> and put it again it display my video )

here is the code

const videoIDContext = React.createContext({
  video:"",
  setVideo: () => {}
});

function UserMain() {
  const [video, setVideo] = useState("");
  return (
    <Grid container direction="column" style={{ height: "100%" }}>
    
//some code
       <videoIDContext.Provider value = {[video,setVideo]}>
        <Home video = {video}/>
       </videoIDContext.Provider >

    </Grid>
  );
}


function Home({ video, data, reel, Tips, upload }) {
  return (
//some code

        <Grid item xs="12" md="5" justify="space-around" 
          alignItems="center">
          <UploadElements />
        </Grid>

      <Grid
        container
        item
        xs={12}
        justify="space-evenly"
        alignItems="stretch"
        style={{ margin: "10px" }}
        spacing={2}
      >
        <MainVideo videoSrc={video} videoName="Nature" />

      </Grid>
  );
}
function UploadElements() {

  let videoContext1 = useContext(videoIDContext)

  const submit = async event => {
    event.preventDefault()
// (postVideoAndPpt) this function used to send data to my back end and save my video path in my data base it works fine 
    const resultVideo = await postVideoAndPpt({ppt: file , video: videoFile, Name: Name});
    console.log(resultVideo);
    videoContext1.setVideo(resultVideo.videoPath)
    setVideos([resultVideo.video, ...videos])
    // console.log(pptFiles);
    // console.log(videos);
  }

  return (
<div className="floatingDiv" style={{ height: "200px" }}>
  <form onSubmit={submit} style={{ width: "100%" }}>
       // my inputs  works fine .. just to summarize it its 2 input of type file that user
       // can upload video in it 

   </form>

 </div>
  );
}

am I missing any thing here ?


Solution

  • so i found an answer, my video id was received successfully in the child but not rendered,so what i need to do is add Key in my video display like this

    <video key={videoSrc} className="video" width="100%" controls>
         <source src={videoSrc} type="video/mp4" />
    </video>
    

    so when this key changes it rerender alone itself