skip to Main Content

I have tried multiple ways. Watched many solutions above but still couldn’t solve this issue. Can anyone please help me using context in my project.

SearchContext.jsx

import { createContext } from 'react';

const SearchContext = createContext();

export default SearchContext;

Search.jsx

import * as React from 'react';
import { useState, useContext } from 'react';
import Paper from '@mui/material/Paper';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import SearchIcon from '@mui/icons-material/Search';
import { Box, IconButton, InputBase } from '@mui/material';
import SearchContext from '../Context/SearchContext';

export default function Search() {
    const [searchQuery, setSearchQuery] = useState('');
    const handleSubmit = (event) => {
        event.preventDefault();
    };

    const handleInputChange = (event) => {
        setSearchQuery(event.target.value);
    };
    return (
        <SearchContext.Provider value={searchQuery} >
            <Box display='flex' alignItems='center' justifyContent='center' paddingTop='20px'>
                <Paper component="form" sx={{ p: '2px 10px', display: 'flex', width: '50%' }} onSubmit={handleSubmit}>
                    <IconButton type="button" sx={{ p: '10px' }} aria-label="search">
                        <AccountCircleIcon fontSize='large' />
                    </IconButton>
                    <InputBase
                        sx={{ ml: 1, flex: 1 }}
                        placeholder="Search User"
                        inputProps={{ 'aria-label': 'search user' }}
                        onChange={handleInputChange}
                    />
                    <IconButton type="submit" sx={{ p: '10px' }} aria-label="search">
                        <SearchIcon fontSize='large' />
                    </IconButton>
                </Paper>
            </Box>
        </SearchContext.Provider>
    );
}

This is how I have used. Is it correct ?
I have later on used it here

import React, { useContext, useEffect, useState } from 'react';
import { ApiService } from '../../API/ApiService';
import SearchContext from '../../Context/SearchContext';


function NumberOfContestParticipated({ handle }) {
    const [contestCount, setContestCount] = useState(null);
    const searchQuery = useContext(SearchContext);
    console.log(searchQuery);
    useEffect(() => {
        const fetchData = async () => {
            const ratingUrl = `https://codeforces.com/api/user.rating?handle=${handle}`;
            const ratingData = await ApiService(ratingUrl);

            if (ratingData && ratingData.status === 'OK') {
                setContestCount(ratingData.result.length);
            } else {
                setContestCount(0);
            }
        };

        fetchData();
    }, [handle]);

    return (
        <div>
            {contestCount !== null ? (
                <p>Number of contests participated by {handle}: {contestCount}</p>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
}

export default NumberOfContestParticipated;

But when I console log the searchQuery , it gives undefined value. What am I doing wrong ?

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import SearchContext from './Context/SearchContext';

ReactDOM.render(
  <SearchContext.Provider>
    <App />
  </SearchContext.Provider>
  , document.getElementById('root')
);

2

Answers


  1. I think your problem is that the NumberOfContestParticipated component is not a child of the Provider component and so the context remains undefined when the state changes. Also it seems weird to me that you are wrapping your application inside the provider twice, there is no need for that if you are wrapping the entire App component.

    Check out this article for more information on how to use context.

    Login or Signup to reply.
  2. For Create Context set initials to the context

    SearchContext.jsx

    const SearchContext = createContext({
      searchQuery: "",
      setSearchQuery: () => {},
    });
    
    

    For set Provider use like This
    create this in SearchContext.jsx and export it

    export const SearchContextProvider = ({ children }) => {
      const [searchQuery, setSearchQuery] = useState("");
    
      return (
        <SearchContext.Provider value={{searchQuery, setSearchQuery}}>
          {children}
        </SearchContext.Provider>
      );
    };
    

    Use of Context

    Search.jsx

    export default function Search() {
       const { searchQuery, setSearchQuery } = useContext(SearchContext);
    
        const handleSubmit = (event) => {
            event.preventDefault();
        };
    
    

    App.js

    <SearchContextProvider>
      <App />
    </SearchContextProvider>;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search