1

Context that I created to use useState across my component:

context.js:

const searchContext = React.createContext();

This is where I created a useState with searchText with initial state as an empty string.

Header.js:

import { useState } from "react";
import { searchContext } from "./context";
import { useSelector } from 'react-redux';
import Motherboard from "./Components/Motherboard";
function Header() {
 const[searchText,setSearchText] = useState("");
 const cart = useSelector(state => state.cart);
 return (
 <div
 style={{ backgroundColor: "#191C27", paddingLeft: 0, paddingRight: 0 }}
 >
 <Navbar
 variant="light"
 expand="lg"
 style={{ backgroundColor: "#191C27" }}
 >
 <Container>
 <Navbar.Toggle aria-controls="navbarScroll">
 <img src={options} alt="options" width="30px" />
 </Navbar.Toggle>
 <Navbar.Brand className="mr-auto" href="#">
 <Link to='home'>
 <img
 className="logoIcon"
 src={logo}
 alt="logo"
 style={{ width: 130 }}
 />
 </Link> 
 </Navbar.Brand>
 <Navbar.Collapse id="navbarScroll">
 <Nav
 className="ml-auto my-2 my-lg-0"
 style={{ maxHeight: "100px", marginRight: "5%" }}
 navbarScroll
 >
 <Nav.Link>
 <Link to='/motherboard' className="links">
 Motherboard
 </Link>
 </Nav.Link>
 <Nav.Link onClick={(e) => e.preventDefault()}>
 <Link to='/processor' className="links">
 Processor
 </Link>
 </Nav.Link>
 <Nav.Link>
 <Link to='/ram' className="links">
 RAM
 </Link>
 </Nav.Link>
 <Nav.Link>
 <Link to='/hdd' className="links">
 HDD
 </Link>
 </Nav.Link>
 <Nav.Link>
 <Link to='/graphic' className="links">
 Cabinet
 </Link>
 </Nav.Link>
 </Nav>
 </Navbar.Collapse>
 <Form className="d-flex" style={{ marginRight: "2%" }}> 
 <searchContext.Provider value={searchText}>
 <Motherboard></Motherboard>
 </searchContext.Provider>
 <FormControl
 type="search"
 placeholder="Search"
 onChange={event => {setSearchText(event.target.value)}}
 className="mr-2"
 aria-label="Search"
 style={{background:'transparent', borderRadius:0, color:'white'}}
 />
 </Form>

Now I tried using my useContext and called the useState value searchText here in Motherboard component. But getting some undefined errors while running.

Motherboard.js:

import {searchContext} from '../context'
const dummy = Array.from(Array(10));
function Motherboard(props) {
 let context = useContext(searchContext);
 const [loading, setLoading] = React.useState(true);
 // const [products, setProducts] = React.useState([]);
 const products = useSelector((state) => state.products);
 const dispatch = useDispatch();
 useEffect(() => {
 axios
 .post("/product?limit=50&page=1&category=motherboard")
 .then((res) => {
 console.log(res, "res");
 dispatch({
 type: actionTypes.GET_PRODUCTS,
 payload: res.data.products,
 });
 setLoading(false);
 })
 .catch((err) => {
 setLoading(false);
 console.log(err);
 });
 }, []);
 const styleCol = {
 backgroundColor: "#0F0F13",
 };
 if (loading) {
 return (
 <div className='loadDiv'>
 <ClipLoader size="150" color="white" style={{marginTop: -200}}/>
 </div>
 );
 }
 return (
 <div className="filterDiv">
 <Banner />
 <Container fluid="md">
 <Row>
 <Col lg={3} style={styleCol} className="colFilter">
 <div>
 <div style={{ backgroundColor: "#191C27" }}>
 <Accordion>
 <AccordionSummary
 aria-controls="panel1a-content"
 id="panel1a-header"
 >
 <Typography>SORT BY PRICE</Typography>
 </AccordionSummary>
 <div className="filterDiv">
 <AccordionDetails>
 <FormControl component="fieldset">
 <RadioGroup aria-label="gender" name="gender1">
 <FormControlLabel
 value="hightolow"
 control={<Radio />}
 label="Highest to Lowest"
 className="radioBtn"
 />
 <FormControlLabel
 value="lowtohigh"
 control={<Radio />}
 label="Lowest to Highest"
 className="radioBtn"
 />
 </RadioGroup>
 </FormControl>
 </AccordionDetails>
 </div>
 </Accordion>
 </div>
 <div style={{ backgroundColor: "#191C27" }}>
 <Accordion>
 <AccordionSummary
 aria-controls="panel1a-content"
 id="panel1a-header"
 >
 <Typography className="heading">SUB CATEGORY</Typography>
 </AccordionSummary>
 <div className="filterDiv">
 <AccordionDetails>
 <FormControl component="fieldset">
 <RadioGroup aria-label="processor" name="prcocessor">
 <FormControlLabel
 value="hightolow"
 control={<Radio />}
 label="INTEL"
 className="radioBtn"
 />
 <FormControlLabel
 value="lowtohigh"
 control={<Radio />}
 label="AMD"
 className="radioBtn"
 />
 </RadioGroup>
 </FormControl>
 </AccordionDetails>
 </div>
 </Accordion>
 </div>
 </div>
 </Col>
 <Col
 xs={12}
 lg={9}
 sm={12}
 md={12}
 style={{ backgroundColor: "#0F0F13", paddingTop: 27 }}
 >
 <Row>
 {products.filter((product) => {
 if(context.searchText == '') {
 return product
 }
 else if(product.productName.toLowerCase.includes(context.searchText.toLowerCase())){
 return product
 }}).map((product, index) => {
 return (
 <Col key={index} lg={4} md={6} xs={12} sm={6}>
 <div
zhulien
5,8254 gold badges25 silver badges41 bronze badges
asked Jul 17, 2021 at 8:20

3 Answers 3

1

you can try to define value as object. the error is probably due to the value not being an object

<searchContext.Provider value={{ searchText }}>
 <Motherboard></Motherboard>
</searchContext.Provider>
answered Jul 17, 2021 at 8:28
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but now I'm getting 'includes is not a function' errors. Does this has anything to do with the change ?
1

As you wrote context.searchText, you have to store an object inside the value of the provider:

<searchContext.Provider value={{ searchText }}>
 <Motherboard />
</searchContext.Provider>
answered Jul 17, 2021 at 8:29

Comments

0

use context instead of context.searchText in MotherBoard.js because you are passing a string as the value in the provider so when call the context using useContext , it gives the latest value of the provider which is what you typed in the search box.

answered Jul 17, 2021 at 9:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.