I have a Search.jsx file where I take the username as input from the user. I want to pass the username to the rest of my project, so I decided to use a context. However, I am encountering an issue where I'm getting an undefined value when I try to access the username in other files using the context. When I console log it, it shows as undefined. Below are my files :-
Search.jsx
import * as React from 'react';
import { useState, createContext } 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';
const SearchContext = createContext();
export default function Search() {
const [searchQuery, setSearchQuery] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
console.log(searchQuery);
};
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>
);
}
export { SearchContext };
File Where I'm trying to get the data
import React, { useContext, useEffect, useState } from 'react';
import { ApiService } from '../../API/ApiService';
import { SearchContext } from '../../Search/Search';
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;
I'm getting undefined when I console log searchQuery.
Index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { SearchContext } from './Search/Search';
ReactDOM.render(
<SearchContext.Provider>
<App />
</SearchContext.Provider>,
document.getElementById('root')
);