I have a functional component. Inside the component, I have called SpecialistsListService service. The service called the API via Axios. I have to test the async function getSpecialistsList and useEffect functions but I don't do that anyone helps me to solve the problem. When I used class component I simply call the method like await wrapper.instance.getSpecialistsList() then check the state but the functional component approach are different I think.
import React, { useState, useEffect } from "react";
import SpecialistsListService from "../../../services/specialists";
import SpecialistsPageView from "./SpecialistsPageView";
import "./index.scss";
export default function SpecialistsPage() {
const [specialistsList, setSpecialistsList] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const specialistsListService = new SpecialistsListService();
useEffect(() => {
getSpecialistsList();
}, []);
async function getSpecialistsList() {
const specialistsListData = await specialistsListService.getSpecialistsList();
setSpecialistsList(specialistsListData);
setIsLoading(false);
}
return (
<SpecialistsPageView isLoading={isLoading} specialists={specialistsList} />
);
}
Splitting your component into custom hooks and component make your life easier to test and more readable by splitting UI and logic.
The custom hooks will look like this
useSpecialistsList.js
import { useState, useEffect } from "react";
const useSpecialistsList = (specialistsListService) => {
const [specialistsList, setSpecialistsList] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
getSpecialistsList();
}, []);
async function getSpecialistsList() {
const specialistsListData = await specialistsListService.getSpecialistsList();
setSpecialistsList(specialistsListData);
setIsLoading(false);
}
return {
isLoading: isLoading,
specialistsList: specialistsList
}
}
export default useSpecialistsList;
The component look like this
import React from "react";
import SpecialistsListService from "../../../services/specialists";
import SpecialistsPageView from "./SpecialistsPageView";
import useSpecialistsList from "./useSpecialistsList";
import "./index.scss";
export default function SpecialistsPage() {
const {isLoading, specialistsList} = useSpecialistsList(new SpecialistsListService());
return (
<SpecialistsPageView isLoading={isLoading} specialists={specialistsList} />
);
}
Now you can test your hooks using "#testing-library/react-hooks"
Test will look like this
import {renderHook} from "#testing-library/react-hooks";
import useSpecialistsList from "./useSpecialistsList";
import SpecialistsListService from "../../../services/specialists";
describe("useSpecialistsList", ()=>{
it('Should return userDetails loading as false', async ()=> {
const {result, waitForNextUpdate} = renderHook(()=> useSpecialistsList(new SpecialistsListService()));
expect(result.current.isLoading).toEqual(true);
await waitForNextUpdate();
expect(result.current.isLoading).toEqual(false);
});
})
Here waitForNextUpdate call the useEffect (Generally update the component)
To read more about testing custom hooks use this like
Related
ProductTable.js
import React, { useEffect, useState } from "react";
function ProductTable() {
useEffect(() => {
fetchData();
}
const fetchData = () => {
axios
.get("http://localhost:4000/api/products/product/viewAllProduct")
.then((res) => {
const getData = res.data.data;
console.log(getData);
setData(getData);
});
};
return ( jsx..)
}
export default ProductTable;
**ProductModals.js
**
``import React, { useEffect, useState } from "react";
function ProductModals(){
const handleSubmit=()=>{
.....
}
return (jsx..)
export default productModals;`
viewProduct.js
import React, { useEffect, useState } from "react";
import ProductTable from "../../Components/Tables/Product/ProductTable";
import ProductModals from "../../Components/Modals/Product/ProductModals";
function viewProduct(){
return(
<productModals/>
<productTable/>
)
}
export default viewProduct;
I need to to get fetchDatafunction from productTable.js component to productModal.js component. both components parent component is viewProduct.js. I tried many ways. but could not work. In productModal.js component has a function for form submit , when form submit done I need to call fetchData function, If anyone know the way please help me
you can do this through react hooks. First, use fetchData into the parent component to pass data into both child components, If needed. Also Once submit the form call fetchData function through it and Update through setData props. So its parent state is also updated.
viewProduct.js
import React, { useEffect, useState } from "react";
import ProductTable from "../../Components/Tables/Product/ProductTable";
import ProductModals from "../../Components/Modals/Product/ProductModals";
useEffect(() => {
fetchData();
}
const fetchData = () => {
axios
.get("http://localhost:4000/api/products/product/viewAllProduct")
.then((res) => {
const getData = res.data.data;
console.log(getData);
setData(getData);
});
};
return ( jsx..)
}
function viewProduct(){
return(
<productModals data={data} setData={setData}/>
<productTable data={data}/>
)
}
export default viewProduct;
productModel.js
Now, Submit your form and call the function recall inside and after getting response update through setData props.
const fetchData = () => {
axios
.get("http://localhost:4000/api/products/product/viewAllProduct")
.then((res) => {
const getData = res.data.data;
console.log(getData);
setData(getData);
});
};
const recall=useCallback(()=>fetchData(),[])
If the scenario is as simple as the example you have provided you can get away with lifting state up, but if you have many nested child components that needs to read/set these states you can use context, as suggested by Rajesh.
Lifting state up
To "lift state up" create a state in the parent component ViewProduct and pass along the relevant variables to the respective components via props:
function ViewProduct(){
const [done, setDone] = useState(false);
return(
<productModals setDone={setDone} />
<productTable done={done} />
)
}
Use the passed in prop setDone in your handleSubmit function to update the state:
function ProductModals({setDone}){
const handleSubmit=()=>{
.....
setDone(true);
}
And in ProductTable make useEffect dependant on done to only fetch when it is true:
function ProductTable({done}) {
useEffect(() => {
if (!done) return;
fetchData();
}, [done]);
const fetchData = () => {
axios
.get(...
Reuse state
If you need to reuse the done state, you can reset it by passing setDone to ProductTable and set it back to false when fetching data:
function ProductTable({done, setDone}) {
useEffect(() => {
if (!done) return;
fetchData();
setDone(false);
}, [done]);
const fetchData = () => {
axios
.get(...
I'm learned that React will re-render after state changed e.g. setState from useState(), calling the function or variable from useContext() variable. But now I'm don't understand that why I get the ESLint warning call the context function inside the useCallback() without dependency in the list. If I put the dependency in the list, useCallback() will be re-rendered and useEffect() dependency from useCallback() variable will do again. So how to fix the react-hooks/exhaustive-deps when calling the function inside the useContext() variable?
Auth.js
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import * as AuthAPI from "../API/AuthAPI"
import Loading from "../Page/Loading"
const AuthContext = createContext()
export const AuthProvider = ({children}) => {
const [user,setUser] = useState()
const [loadingInitial,setLoadingInitial] = useState(true)
useEffect(()=>{
AuthAPI.getCurrentUser()
.then((user)=>setUser(user))
.catch((error)=>{console.log(error)})
.finally(()=>setLoadingInitial(false))
},[])
const login = async (email,password) => {
const user = await AuthAPI.login({email,password})
setUser(user)
return user
}
const register = async (firstname,lastname,email,password) => {
const user = await AuthAPI.register({firstname,lastname,email,password})
setUser(user)
return user
}
const logout = async () => {
const response = await AuthAPI.logout()
setUser(undefined)
}
const value = useMemo(()=>({
user,
setUser,
login,
register,
logout
}),[user])
return (
<AuthContext.Provider value={value}>
{loadingInitial ? <Loading/> : children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
return useContext(AuthContext)
}
Logout.js
import { useCallback, useEffect, useState } from "react";
import { Navigate, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../Hooks/Auth";
import * as AuthAPI from "../API/AuthAPI"
import Loading from "./Loading";
function Logout() {
const auth = useAuth()
const location = useLocation()
const navigate = useNavigate()
const [isLoggedOut,setIsLoggedOut] = useState(false)
const logout = useCallback(async () => {
console.log("Logging out!")
await AuthAPI.logout()
auth.setUser((prevState)=>(undefined))
setIsLoggedOut(true)
},[auth]) // --> re-rendered bacause `auth` context in re-rendered when set `user` state.
useEffect(()=>{
logout()
},[logout]) // --> this also to run again from `logout` callback is being re-rendered.
if (!isLoggedOut) {
return <Loading/>
}
return (
<Navigate to="/login" replace/>
)
}
export default Logout
Any help is appreciated.
How about destructuring your auth context, since you are only using setUser inside useEffect?
const { setUser } = useAuth()
useEffect(() => {
....
}, [setUser])
There is no need for creating a memoized logout callback function if logout isn't used/passed as a callback function. Just apply the logging out logic in the useEffect hook.
Render the Loading component and issue the imperative redirect from the resolved Promise chain of the return AuthAPI.logout Promise.
Example:
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../Hooks/Auth";
import * as AuthAPI from "../API/AuthAPI"
import Loading from "./Loading";
function Logout() {
const auth = useAuth();
const navigate = useNavigate();
useEffect(() => {
console.log("Logging out!");
AuthAPI.logout()
.then(() => auth.setUser(undefined))
.finally(() => navigate("/login", { replace: true }));
}, []);
return <Loading />;
}
export default Logout;
Can you try to replace your useEffect code into this:
useEffect(logout, [])
I'm still new to React so forgive me if this is a silly approach to this problem.
My goal: Global error handling using a context provider and a custom hook.
The Problem: I can't remove errors without them immediately being re-added.
I display my errors via this component in the shell...
import React, { useState, useEffect } from 'react'
import Alert from '#mui/material/Alert'
import Collapse from '#mui/material/Collapse'
import { useAlertContext } from '#/context/alert-context/alert-context'
export default function AppAlert () {
const [show, setShow] = useState(false)
const alertContext = useAlertContext()
const handleClose = () => {
alertContext.remove()
setShow(false)
}
useEffect(() => {
if (alertContext.alert) {
setShow(true)
}
}, [alertContext.alert])
return (
<Collapse in={show}>
<Alert severity='error' onClose={handleClose}>
{alertContext.alert}
</Alert>
</Collapse>
)
}
I have a provider setup that also exposes a custom hook...
import React, { useState, createContext, useContext } from 'react'
const AlertContext = createContext()
const AlertProvider = ({ children }) => {
const [alert, setAlert] = useState(null)
const removeAlert = () => setAlert(null)
const addAlert = (message) => setAlert(message)
return (
<AlertContext.Provider value={{
alert,
add: addAlert,
remove: removeAlert
}}
>
{children}
</AlertContext.Provider>
)
}
const useAlertContext = () => {
return useContext(AlertContext)
}
export {
AlertProvider as default,
useAlertContext
}
And finally I have a hook setup to hit an API and call throw errors if it any occur while fetching the data. I'm purposely triggering a 404 by passing a bad API path.
import { useEffect } from 'react'
import { useQuery } from 'react-query'
import ApiV4 from '#/services/api/v4/base'
import { useAlertContext } from '#/context/alert-context/alert-context'
export const useAccess = () => {
const alertContext = useAlertContext()
const route = '/accessx'
const query = useQuery(route, async () => await ApiV4.get(route), {
retry: 0
})
useEffect(() => {
if (query.isError) {
alertContext.add(query.error.toString())
}
}, [alertContext, query.isError, query.error])
return query
}
This code seems to be the issue. Because alertContext.remove() triggers useEffect here and query.error still exists, it immediately re-adds the error to the page on remove. Removing alertContext from the array works, but it is not a real fix and linter yells.
useEffect(() => {
if (query.isError) {
alertContext.add(query.error.toString())
}
}, [alertContext, query.isError, query.error])
This is a perfectly fine approach to the problem. You've also accurately identified the problem. The solution is to create a second hook with access to the methods that will modify the context. AppAlert needs access to the data in the context, and needs to update when AlertContext.alert changes. UseAccess only needs to be able to call AlertContext.add, and that method wont change and trigger a re-render. This can be done with a second Context. You can just expose one Provider and bake the actions provider into the outer context provider.
import React, { useState, createContext, useContext } from 'react'
const AlertContext = createContext()
const AlertContextActions = createContext()
const AlertProvider = ({ children }) => {
const [alert, setAlert] = useState(null)
const removeAlert = () => setAlert(null)
const addAlert = (message) => setAlert(message)
return (
<AlertContext.Provider value={{ alert }}>
<AlertContextActions.Provider value={{ addAlert, removeAlert }}>
{children}
</AlertContextActions.Provider>
</AlertContext.Provider>
)
}
const useAlertContext = () => {
return useContext(AlertContext)
}
export {
AlertProvider as default,
useAlertContext
}
Now, where you need access to the alert you use one hook and where you need access to the actions you use the other.
// in AppAlert
import { useAlertContext, useAlertContextActions } from '#/context/alert-context/alert-context'
...
const { alert } = useAlertContext()
const { removeAlert } = useAlertContextActions()
And finally
// in useAccess
import { useAlertContextActions } from '#/context/alert-context/alert-context'
...
const { addAlert } = useAlertContextActions()
So I found a solution that seems to work for my purposes. I got a hint from this article. https://mortenbarklund.com/blog/react-architecture-provider-pattern/
Note the use of useCallback above. It ensures minimal re-renders of components using this context, as the function is guaranteed to be stable (as its memoized without dependencies).
So with this I tried the following and it solved the problem.
import React, { useState, createContext, useContext, useCallback } from 'react'
const AlertContext = createContext()
const AlertProvider = ({ children }) => {
const [alert, setAlert] = useState(null)
const removeAlert = useCallback(() => setAlert(null), [])
const addAlert = useCallback((message) => setAlert(message), [])
return (
<AlertContext.Provider value={{
alert,
add: addAlert,
remove: removeAlert
}}
>
{children}
</AlertContext.Provider>
)
}
const useAlertContext = () => {
return useContext(AlertContext)
}
export {
AlertProvider as default,
useAlertContext
}
My goal: Global error handling
One problem with the above useEffect approach is that every invocation of useAccess will run their own effects. So if you have useAccess twice on the page, and it fails, you will get two alerts, so it's not really "global".
I would encourage you to look into the global callbacks on the QueryCache in react-query. They are made for this exact use-case: To globally handle errors. Note that to use context, you would need to create the queryClient inside the Application, and make it "stable" with either useRef or useState:
function App() {
const alertContext = useAlertContext()
const [queryClient] = React.useState(() => new QueryClient({
queryCache: new QueryCache({
onError: (error) =>
alertContext.add(error.toString())
}),
}))
return (
<QueryClientProvider client={queryClient}>
<RestOfMyApp />
</QueryClientProvider>
)
}
I also have some examples in my blog.
I'm trying to pass data with Context API to child components. Value is getting undefined upon fetching it from a component.
Component Hierarchy:
passing data to a component MockTable and UsecasePane
MainContent -> MockTable
MainContent -> AddMock -> TabContent -> UsecasePane
=> MockContext.js
import React, { useState, useEffect, createContext } from "react";
import axios from "axios";
export const MockContext = createContext();
// provider
export const MockProvider = (props) => {
const [data, setData] = useState([]);
// data fetch and setting the state
return (
<MockContext.Provider data={[data, setData]}>
{props.children}
</MockContext.Provider>
);
};
Note: I'm getting response from the API.
Now in MainContent, components are encapsulated as follows:
// MainContent.js
import React from "react";
import { MockProvider } from "../MockContext";
const MainContent = () => {
return (
<MockProvider>
<div>
<CustomerTable />
<AddMock />
<MockTable />
</div>
</MockProvider>
);
};
When I try to fetch the data in MockTable or in UseCasePane, value is undefined.
// MockTable.js
import React, { useState, useEffect, useContext } from "react";
import { MockContext } from "./MockContext";
const MockTable = () => {
const [data, setData] = useContext(MockContext);
console.log(data);
// rest of the code
}
Please correct me where I'm going wrong :)
I tried to pass a String as well from the context and fetched in a component like:
return (
<MockContext.Provider data={"Hello"}>
{props.children}
</MockContext.Provider>
);
// in MockTable.js
const value = useContext(MockContext); ==> undefined
The correct prop to pass into the Provider is value, not data. (See: Context.Provider)
import React, { useState, useEffect, createContext } from "react";
import axios from "axios";
export const MockContext = createContext();
// provider
export const MockProvider = (props) => {
const [data, setData] = useState([]);
const fetchData = async () => {
const response = await axios
.get(config.App_URL.getAllRoute, {
params: {
customHostName: config.host,
type: config.type,
},
})
.catch((error) => {
console.error(`Error in fetching the data ${error}`);
});
console.log(response.data);
setData(response.data);
};
useEffect(() => {
fetchData();
}, []);
return (
<MockContext.Provider value={[data, setData]}>
{props.children}
</MockContext.Provider>
);
};
I have a React app that I need to test. It's using the useContext() hook to create Provider that are using in most of my components. I have a dedicated component to handle a Context (lets say UserContext for the example) that look like that:
UserContext.jsx:
import React from 'react'
export const UserContext = React.createContext(undefined)
export const UserProvider = (props) => {
const [currentUser, setCurrentUser] = React.useState(undefined)
const context = {
currentUser,
setCurrentUser,
}
return (
<UserContext.Provider value={context}>
{props.children}
</UserContext.Provider>
)
}
So you can use the Provider like that:
import { UserProvider } from './context/UserContext'
<UserProvider>
{ ... }
</UserProvider>
Now I need to test a component that use this UserContext so let's say UserModal:
UserModal.test.jsx
import React from 'react'
import { mount } from 'enzyme'
import { BrowserRouter as Router } from 'react-router-dom'
import { UserProvider, UserContext } from '../context/UserContext'
import UserModal from '../components/UserModal'
// D A T A
import exampleUser from '../data/user.json' // Load user's data from a json file
describe('<UserModal />', () => {
let wrapper
const Wrapper = () => {
const { setCurrentUser } = React.useContext(UserContext)
React.useEffect(() => {
// Init UserContext value
setCurrentUser(exampleUser)
}, [])
return (
<UserProvider>
<UserModal />
</UserProvider>
)
}
beforeEach(() => {
wrapper = mount(<Wrapper />)
})
})
Problem is that when <UserModal /> is mounted inside of the <UserProvider>, I get an error that the currentUser in the UserContext is undefined. This error make sense because I call setCurrentUser() when the component is mounted once using React.useEffect(() => { }, []).
So have you an idea how I can mount() my <UserModal /> component inside of a context's provider in the way that the context is not undefined?
Your test should look like this:
import React from 'react'
import { mount } from 'enzyme'
import { BrowserRouter as Router } from 'react-router-dom'
import { UserProvider, UserContext } from '../context/UserContext'
import UserModal from '../components/UserModal'
// D A T A
import exampleUser from '../data/user.json' // Load user's data from a json file
describe('<UserModal />', () => {
let wrapper
const Wrapper = () => {
const { setCurrentUser } = React.useContext(UserContext)
React.useEffect(() => {
// Init UserContext value
setCurrentUser(exampleUser)
}, [])
return (
<UserModal />
)
}
beforeEach(() => {
wrapper = mount(<UserProvider><Wrapper /></UserProvider>)
})
})
Or see codesandbox here - simple test passes.
Note that UserProvider wraps Wrapper and not is used inside. It's like this because if you are using it inside, there is no UserContext to get with useContext hook, therefore there is no setCurrentUser function.