React custom hooks not working as expected - reactjs

I am trying to implement a very simple custom hook called useOpen that simply returns a boolean (isOpen). I want to show or hide some text in App.js based on isOpen state. Currently, nothing is being rendered and trying to console.log(isOpen) in App.js gives me undefined. Thanks in advance!
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
const {isOpen} = useOpen;
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
return { isOpen }
}

You’re missing the parens on useOpen. Should be useOpen().
const {isOpen} = useOpen; // missing ()
const {isOpen} = useOpen();

Try to call function useOpen at the component.

you need to execute the hook to get its value
and you don't need to put it in a object to deconstruct it on the other side
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
//const {isOpen} = useOpen;
const isOpen = useOpen();
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
//return { isOpen }
return isOpen
}

Related

How do I get a state variable from child to parent?

I am learning React.
I have Component structure like this -
index.js
import React from "react";
import Button from "./Button/Button"
export default function Index() {
return (
<>
<Button />
<div>Value of flag in Index.js = {}</div>
</>
);
}
Button.js
import React, { useState } from "react";
import "./button.css";
export default function Button(props) {
const [flag, setFlag] = useState(true);
const clickHandler = () => {
setFlag(!flag);
};
return (
<div className="btn" onClick={clickHandler}>
Value of flag in Button.js = {flag.toString()}
</div>
);
}
My question is "How do I get flag value from Button.js to index.js" ? (child to parent).
1) You can lift state in parent component and pass state and handler as a prop to children.
Note: This is will work because you need flag in the JSX, But if you will pass event handler as a prop in the child component then you have to invoke the handler to get the value. So Either lift the state or use Redux
Live Demo
App.js
const App = () => {
const [flag, setFlag] = useState( true );
return (
<>
<Button flag={flag} setFlag={setFlag} />
<div>Value of flag in Index.js = { flag.toString() }</div>
</>
);
};
Button.js
export default function Button({ flag, setFlag }) {
const clickHandler = () => {
setFlag(oldFlag => !oldFlag);
};
return (
<div className="btn" onClick={clickHandler}>
Value of flag in Button.js = {flag.toString()}
</div>
);
}
2) You can pass handler as a prop in child component as shown in the Harsh Patel answer
3) You can use state management tool i.e. Redux.
You can send a value by method, refer to this:
index.js
import React from "react";
import Button from "./Button/Button"
export default function Index() {
let getFlagValue = (flag) => {
//here you'll get a flag value
console.log(flag)
}
return (
<>
<Button sendFlagValue=(getFlagValue)/>
<div>Value of flag in Index.js = {}</div>
</>
);
}
Button.js
import React, { useState } from "react";
import "./button.css";
export default function Button(sendFlagValue) {
const [flag, setFlag] = useState(true);
const clickHandler = () => {
setFlag(!flag);
sendFlagValue(flag)
};
return (
<div className="btn" onClick={clickHandler}>
Value of flag in Button.js = {flag.toString()}
</div>
);
}
There are two types state:
global state for all
private state for component
For starter, you must obey some policies, not try abuse state, otherwise you will have some troubles.
For global STATE, you can use Redux or dva or umijs.
For private STATE, you seems already known.

arrow function inside functional component is undefined react hooks

I'm trying to make a like button counter with react hooks. I have defined the arrow function this way, but I'm getting IncreaseLikeHandler is undefined.
import {useState} from "react";
import './App.css';
function App() {
IncreaseLikeHandler = () =>{
setLikeCounter(likeCounter+1);
};
const [likeCounter, setLikeCounter] = useState(0);
const [dislikeCounter, setDislikeCounter] = useState(0);
return (
<div className="App">
<p>test</p>
<button onClick={IncreaseLikeHandler}>like</button>
<button>dislike</button>
<div>{likeCounter}</div>
</div>
);
}
export default App;
You first have to declare it then you can use it
without declaration eslint will complain
'IncreaseLikeHandler' is not defined. (no-undef)eslint
const IncreaseLikeHandler = () => {
setLikeCounter(likeCounter + 1);
};
Inside the fanction component you must use (const, let and var) to define the functions.

ref.current is always undefined?

I need to use functional component ,so I can't use useRef directly. here is my code:
import React,{forwardRef,useImperativeHandle,useRef,useEffect} from "react";
import "./style.css";
export default function App() {
const ref_ = useRef();
useEffect(()=>{
console.log(ref_)
})
console.log(ref_)
return (
<div>
<Demo/>
</div>
);
}
const Demo = forwardRef((props,ref)=>{
useImperativeHandle(ref,()=>({
toggle(){
console.log(123);
}
}))
return(
<div ref={ref}>1234</div>
)
})
online code :
https://stackblitz.com/edit/forwardref-z68drh?file=src/App.js
and I want to trigger child component's function on parent component... can anyone help me?
You need to pass the ref itself to Demo component:
function App() {
const ref = useRef();
return <Demo ref={ref}/>;
}
Then you can use ref.current.toggle() due to useImperativeHandle.
https://stackblitz.com/edit/forwardref-z68drh-epz2xf?file=src/App.js

How to test code that uses a custom hook based on useContext with react-testing-library and jest

I've created a custom context hook - and I'm struggling to figure out how to pass values to its provider during testing.
My hook:
import React, { createContext, useContext, useState } from 'react';
const Context = createContext({});
export const ConfigurationProvider = ({ children }) => {
// Use State to keep the values
const [configuration, setConfiguration] = useState({});
// pass the value in provider and return
return (
<Context.Provider
value={{
configuration,
setConfiguration,
}}
>
{children}
</Context.Provider>
);
};
export const useConfigurationContext = () => useContext(Context);
export const { Consumer: ConfigurationConsumer } = Context;
This is how it's used in the application:
function App() {
return (
<ConfigurationProvider>
<div className="app">
<ComponentA />
</div>
</ConfigurationProvider>
);
}
And in ComponentA:
const ComponentA = () => {
// Get configuration
const configuration = useConfigurationContext();
return (
<div>{JSON.stringify(configuration)}</div>
)
}
This all works fine - considered that I'm calling setConfiguration from another component and set an object. Now for the testing part:
import React, { Component, createContext } from 'react';
import { render, waitFor } from '#testing-library/react';
import ComponentA from 'componentA';
const config = {
propertyA: 'hello',
};
test('renders the config', async () => {
const ConfigurationContext = createContext();
const { queryByText } = render(
<ConfigurationContext.Provider value={config}>
<ComponentA />
</ConfigurationContext.Provider>
);
expect(queryByText('hello')).toBeInTheDocument();
});
This doesn't work - I'm expecting the value that I'm sending in would be rendered in the div, but the context is an empty object. What am I doing wrong?
Thanks to Carle B. Navy I got the reason why it doesn't work. For other people two wonder what the solution is I fixed it by doing the following:
In my context hook, I changed the last line to export the provider as well:
export const { Consumer: ConfigConsumer, Provider: ConfigProvider } = Context;
Then in my test case, instead of creating a new context, I import the ConfigProvider at the top, and then:
const { queryByText } = render(
<ConfigProvider value={config}>
<ComponentA />
</ConfigProvider>
);
Thanks for helping me solve this and hope this helps someone else.

Why am I getting "useContext is not a function" or "context is not defined"?

I am trying to use context in my stateless component. I updated my react to v16.8.0 and added useContext, however, I keep getting these two errors and don't know what else to do. Here is my code:
import React, { useState } from "react";
import axios from "axios";
import { LanguageContext } from "./languageContext";
import { useContext } from "react";
function StripeButton() {
const context = useContext(LanguageContext);
const stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");
const [error, setError] = useState();
const handleClick = () => {
stripe
.redirectToCheckout({
...
});
};
return (
<div>
<button
id="UrgentCheckedButtonYES"
className="btn-primary"
onClick={handleClick}
>
{this.context.main.name}
<br />
</button>
<div>{error}</div>
</div>
);
}
export default StripeButton;
StripeButton.contextType = LanguageContext;
You need to import useContext like this:
import { useContext } from 'react';
const { useContext } = React
useContext is exported as method property of React
(Tested this in React 18.)
In App.js File:
import { createContext } from "react";
import ChildComponent from "./components/ChildComponent";
export const Context = createContext("Default Value");
export default function App() {
const value = "My Context Value";
return (
<Context.Provider value={value}>
<ChildComponent />
</Context.Provider>
);
}
In ChildComponent.jsx file:
import { useContext } from "react";
import { Context } from "../App";
function ChildComponent() {
const value = useContext(Context);
return <h1>{value}</h1>;
}
export default ChildComponent;
You can have as many consumers as you want for a single context. If the context value changes,then all consumers are immediately notified and re-rendered.
If the consumer isn't wrapped inside the provider, but still tries to access the context value (using useContext(Context) or <Context.Consumer>), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context.

Resources