I am trying to test a component that use context. After I mount it (shallow does not work with useContext apparently) I am trying to set default values for the component data.
I was expecting const contextValues = { text: 'mock', msg: 'SUCCESS' }; and passing that to the AlertContextProvider to set a state for that component but I am probably looking at this the wrong way.
AlertContext.js:
import React, { createContext, useState, useContext } from 'react';
export const AlertContext = createContext();
const AlertContextProvider = props => {
const [alert, setAlert] = useState({
text: '',
msg: ''
});
const updateAlert = (text, msg) => {
setAlert({
text,
msg
});
};
return (
<AlertContext.Provider value={{ alert, updateAlert }}>
{props.children}
</AlertContext.Provider>
);
};
export default AlertContextProvider;
Alert.js (component):
import React, { useContext } from 'react';
import './Alert.scss';
import { AlertContext } from '../context/AlertContext';
const Alert = () => {
const { alert } = useContext(AlertContext);
return (
<div className='alert'>
<p className="alert-para">{alert.text}</p>
</div>
);
};
export default Alert;
Alert.js(text)
import React from 'react';
import { mount } from 'enzyme';
import Alert from '../components/Alert';
import AlertContextProvider from '../context/AlertContext';
describe('Alert', () => {
let wrapper;
beforeEach(() => {
const contextValues = { text: 'mock', msg: 'SUCCESS' };
// Below mounting is needed as Enzyme does not yet support shallow mocks
wrapper = mount(
<AlertContextProvider value={contextValues}>
<Alert />
</AlertContextProvider>
);
});
test('Should render a paragraph', () => {
const element =wrapper.find('.alert-para');
expect(element.length).toBe(1); // this is correct
expect(element.text()).toEqual('mock'); // THIS FAILS AS THE VALUE OF THE ELEMENT IS AN EMPTY STRING WHILE I WAS EXPECTING 'mock'
});
});
You are passing your contextValues through value prop on <AlertContextProvider /> but you are never using that prop to initialize data inside your context provider.
In this example, I used useEffect hook as componentDidMount to initialize your state AlertContext.js`
const AlertContextProvider = props => {
const [alert, setAlert] = useState({
text: '',
msg: ''
});
// The same as component did mount
useEffect(() => {
setAlert({
text: props.value.text,
msg: props.value.msg
})
}, [])
const updateAlert = (text, msg) => {
setAlert({
text,
msg
});
};
return (
<AlertContext.Provider value={{ alert, updateAlert }}>
{props.children}
</AlertContext.Provider>
);
};
You should use useCallback hook for your updateAlert function to memoize it.
Related
So I've been learning to use useContext and useReducer hooks with action/dispatch and whenever I try to use dipatch function from any component, it throws out "Uncaught TypeError: dispatch is not a function" error.. it's been 5 days now:/
I try to access dispatch function in the following manner inside components
// context
import { ModalContext } from "../Context/Contexts/ModalContext";
import { OPEN_IMAGE_MODAL } from "../Context/action.types";
const { dispatch } = useContext(ModalContext);
dispatch({
type: OPEN_IMAGE_MODAL,
payload: { isEnabled: true, imageDetails: { url: doc.url } },
});
Here are the ref files
App.js
import React from "react";
// components
import Nav from "./Components/Nav";
import ImageUploadForm from "./Components/ImageUploadForm";
import ImageGrid from "./Components/ImageGrid";
// context
import { ModalContextProvider } from "./Context/Contexts/ModalContext";
const App = () => {
return (
<div className="App">
<Nav />
<ImageUploadForm />
<ModalContextProvider>
<ImageGrid/>
</ModalContextProvider>
</div>
);
};
export default App;
ModalContext.js (Context & Context Provider creation)
import { createContext, useReducer } from "react";
// reducer
import { modalReducer } from "../Reducers/modalReducer";
// components
import ImageModal from "../../Components/ImageModal";
// creating and exporting context
export const ModalContext = createContext();
const initialState = { isEnabled: false, imageDetails: {} };
export const ModalContextProvider = ({ children }) => {
// for selected/clicked image
const [isEnabled, imageDetails, dispatch] = useReducer(
modalReducer,
initialState
);
return (
<ModalContext.Provider value={{ isEnabled, imageDetails, dispatch }}>
{children}
{isEnabled && <ImageModal />}
</ModalContext.Provider>
);
};
modalReducer.js (reducer fn)
import { OPEN_IMAGE_MODAL, CLOSE_IMAGE_MODAL } from "../action.types";
export const modalReducer = (state, action) => {
switch (action.type) {
case OPEN_IMAGE_MODAL:
return {
...state,
isEnabled: true,
imageDetails: action.payload.imageDetails,
};
case CLOSE_IMAGE_MODAL:
return { ...state, isEnabled: false, imageDetails: {} };
default:
return { ...state };
}
};
useReducer returns an array with exactly two values. You are assuming there is some third value dispatch, which is actually undefined. And undefined is not a function.
Depending on how many values you want to passdown using context you can fix this. I like to pass only two values, one state and one dispatch.
const [state, dispatch] = useReducer(
modalReducer,
initialState
);
return (
<ModalContext.Provider value={{ state, dispatch }}>
{children}
{state.isEnabled && <ImageModal />}
</ModalContext.Provider>
);
In children just extract how you do:
const { dispatch } = useContext(ModalContext);
I think the useReducer hook just can return 2 arrays, the satate and the dsipatch method.
Error Message: React Hook "useDispatch" is called conditionally. React Hooks must be called in the exact same order in every component render
I've been trying to figure out how to fix this for days, but nothing seeems to work. The component works when I don't mock anything, but as soon as I mock dispatch it gives me this error.
Here's my component:
import { Stage } from "../Stage/Stage";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { retrieveStageList } from "../../modules/reducer";
import { Process } from "../Process/Process";
export function RenderProcess({
_useSelector = useSelector,
_useDispatch = useDispatch(), //this is where it breaks
_Process = Process,
}) {
const dispatch = _useDispatch();
const process = _useSelector((state) => state.renderProcess);
const stageList = _useSelector((state) => state.stageList);
useEffect(() => {
if (process.processId !== null)
dispatch(retrieveStageList(process.processId));
}, []);
return (
<>
<_Process process={process} />
{stageList?.map((stageInputs, processId) => {
return (
<div key={processId}>
<Stage stage={stageInputs} />
</div>
);
})}
</>
);
}
Here's my test for this component:
import { render } from "#testing-library/react";
import { RenderProcess } from "./RenderProcess";
test("should call dispatch once.", () => {
const _useSelector = (fn) =>
fn({
stageList: [],
renderProcess: { processId: "309624b6-9c96-4ba7-8f7e-78831614f685" },
});
const dispatch = jest.fn();
render(
<RenderProcess
_useSelector={_useSelector}
_useDispatch={() => dispatch}
_Process={() => {}}
/>
);
expect(dispatch).toHaveBeenCalledTimes(1);
});
Any help on this would be amazing.
Found the fix, in the properties being passed in RenderProcess- on this
line:
_useDispatch = useDispatch()
it should be:
_useDispatch = useDispatch
I have set a basic sample project that use Context to store the page title, but when I set it the component is not rerendered.
Principal files:
Context.js
import React from 'react'
const Context = React.createContext({})
export default Context
AppWrapper.js
import React from 'react'
import App from './App'
import Context from './Context'
function AppWrapper () {
return (
<Context.Provider value={{page: {}}}>
<App />
</Context.Provider>
)
}
export default AppWrapper
App.js
import React, { useContext } from 'react';
import Context from './Context';
import Home from './Home';
function App() {
const { page } = useContext(Context)
return (
<>
<h1>Title: {page.title}</h1>
<Home />
</>
);
}
export default App;
Home.js
import React, { useContext } from 'react'
import Context from './Context'
function Home () {
const { page } = useContext(Context)
page.title = 'Home'
return (
<p>Hello, World!</p>
)
}
export default Home
full code
What am I doing wrong?
Think about React context just like you would a component, if you want to update a value and show it then you need to use state. In this case your AppWrapper where you render the context provider is where you need to track state.
import React, {useContext, useState, useCallback, useEffect} from 'react'
const PageContext = React.createContext({})
function Home() {
const {setPageContext, page} = useContext(PageContext)
// essentially a componentDidMount
useEffect(() => {
if (page.title !== 'Home')
setPageContext({title: 'Home'})
}, [setPageContext])
return <p>Hello, World!</p>
}
function App() {
const {page} = useContext(PageContext)
return (
<>
<h1>Title: {page.title}</h1>
<Home />
</>
)
}
function AppWrapper() {
const [state, setState] = useState({page: {}})
const setPageContext = useCallback(
newState => {
setState({page: {...state.page, ...newState}})
},
[state, setState],
)
const getContextValue = useCallback(
() => ({setPageContext, ...state}),
[state, updateState],
)
return (
<PageContext.Provider value={getContextValue()}>
<App />
</PageContext.Provider>
)
}
Edit - Updated working solution from linked repository
I renamed a few things to be a bit more specific, I wouldn't recommend passing setState through the context as that can be confusing and conflicting with a local state in a component. Also i'm omitting chunks of code that aren't necessary to the answer, just the parts I changed
src/AppContext.js
export const updatePageContext = (values = {}) => ({ page: values })
export const updateProductsContext = (values = {}) => ({ products: values })
export const Pages = {
help: 'Help',
home: 'Home',
productsList: 'Products list',
shoppingCart: 'Cart',
}
const AppContext = React.createContext({})
export default AppContext
src/AppWrapper.js
const getDefaultState = () => {
// TODO rehydrate from persistent storage (localStorage.getItem(myLastSavedStateKey)) ?
return {
page: { title: 'Home' },
products: {},
}
}
function AppWrapper() {
const [state, setState] = useState(getDefaultState())
// here we only re-create setContext when its dependencies change ([state, setState])
const setContext = useCallback(
updates => {
setState({ ...state, ...updates })
},
[state, setState],
)
// here context value is just returning an object, but only re-creating the object when its dependencies change ([state, setContext])
const getContextValue = useCallback(
() => ({
...state,
setContext,
}),
[state, setContext],
)
return (
<Context.Provider value={getContextValue()}>
...
src/App.js
...
import AppContext, { updateProductsContext } from './AppContext'
function App() {
const [openDrawer, setOpenDrawer] = useState(false)
const classes = useStyles()
const {
page: { title },
setContext,
} = useContext(Context)
useEffect(() => {
fetch(...)
.then(...)
.then(items => {
setContext(updateProductsContext({ items }))
})
}, [])
src/components/DocumentMeta.js
this is a new component that you can use to update your page names in a declarative style reducing the code complexity/redundancy in each view
import React, { useContext, useEffect } from 'react'
import Context, { updatePageContext } from '../Context'
export default function DocumentMeta({ title }) {
const { page, setContext } = useContext(Context)
useEffect(() => {
if (page.title !== title) {
// TODO use this todo as a marker to also update the actual document title so the browser tab name changes to reflect the current view
setContext(updatePageContext({ title }))
}
}, [title, page, setContext])
return null
}
aka usage would be something like <DocumentMeta title="Whatever Title I Want Here" />
src/pages/Home.js
each view now just needs to import DocumentMeta and the Pages "enum" to update the title, instead of pulling the context in and manually doing it each time.
import { Pages } from '../Context'
import DocumentMeta from '../components/DocumentMeta'
function Home() {
return (
<>
<DocumentMeta title={Pages.home} />
<h1>WIP</h1>
</>
)
}
Note: The other pages need to replicate what the home page is doing
Remember this isn't how I would do this in a production environment, I'd write up a more generic helper to write data to your cache that can do more things in terms of performance, deep merging.. etc. But this should be a good starting point.
Here is a working version of what you need.
import React, { useState, useContext, useEffect } from "react";
import "./styles.css";
const Context = React.createContext({});
export default function AppWrapper() {
// creating a local state
const [state, setState] = useState({ page: {} });
return (
<Context.Provider value={{ state, setState }}> {/* passing state to in provider */}
<App />
</Context.Provider>
);
}
function App() {
// getting the state from Context
const { state } = useContext(Context);
return (
<>
<h1>Title: {state.page.title}</h1>
<Home />
</>
);
}
function Home() {
// getting setter function from Context
const { setState } = useContext(Context);
useEffect(() => {
setState({ page: { title: "Home" } });
}, [setState]);
return <p>Hello, World!</p>;
}
Read more on Hooks API Reference.
You may put useContext(yourContext) at wrong place.
The right position is inner the <Context.Provider>:
// Right: context value will update
<Context.Provider>
<yourComponentNeedContext />
</Context.Provider>
// Bad: context value will NOT update
<yourComponentNeedContext />
<Context.Provider>
</Context.Provider>
I am new to React's context API and hooks for function components. I am trying to pass state to a child component, ActivityTable.js. I wrapped the provider around the app (App.js), however state properties are still undefined in ActivityTable.js -- TypeError: Cannot read property 'id' of undefined.
Any guidance would be appreciated.
App.js
import ActivityState from "./context/activities/ActivityState";
const App = () => {
return (
<StylesProvider injectFirst>
<ContactState>
<ActivityState>
...
</ActivityState>
</ContactState>
</StylesProvider>
);
};
export default App;
ActivityState.js
import React, { useReducer } from 'react';
import ActivityContext from './ActivityContext';
import ActivityReducer from './ActivityReducer';
import { ADD_ACTIVITY, DELETE_ACTIVITY, SET_CURRENT_ACTIVITY } from '../types';
const ActivityState = props => {
const initialState = {
activities: [
{
id: 1,
activity_description: "a desc",
activity_name: "a",
},
{
id: 2,
activity_description: "b desc",
activity_name: "b",
},
{
id: 3,
activity_description: "c desc",
activity_name: "c",
}
]
};
const [state, dispatch] = useReducer(ActivityReducer, initialState);
const deleteActivity = id => {
dispatch({ type: DELETE_ACTIVITY, payload: id });
};
const setCurrentActivity = activity => {
dispatch({ type: SET_CURRENT_ACTIVITY, payload: activity });
};
return (
<ActivityContext.Provider
value={{
activities: state.activities,
deleteActivity,
setCurrentActivity
}}>
{ props.children }
</ActivityContext.Provider>
);
}
export default ActivityState;
ActivityContext.js
import { createContext } from "react";
const ActivityContext = createContext(null);
export default ActivityContext;
ActivityReducer.js
import { DELETE_ACTIVITY, SET_CURRENT_ACTIVITY } from '../types';
export default (state, action) => {
switch (action.type) {
case DELETE_ACTIVITY:
return {
...state,
activities: state.activities.filter(
activity => activity.id !== action.payload
)
};
case SET_CURRENT_ACTIVITY:
return {
...state,
current: action.payload
};
default:
return state;
}
};
ActivityView.js
import React, { useContext } from "react";
import ActivityContext from '../../context/activities/ActivityContext';
import ActivityTable from './ActivityTable';
const Activities = () => {
const activityContext = useContext(ActivityContext);
const { activities } = activityContext;
console.log('activities: ', activities);
return (
<div>
<ActivityTable/>
</div>
);
}
export default Activities;
ActivityTable.js
import React, { useContext, useState } from "react";
import ActivityContext from "../../context/activities/ActivityContext";
const ActivityTable = ({ activity }) => { //activity is undefined here
const activityContext = useContext(ActivityContext);
const { activities } = activityContext;
const { id, activity_name, activity_desc } = activity; //undefined
return (
<div>
<tr>
<td>{id}</td>
<td>{activity_name}</td>
<td>{activity_desc}</td>
</tr>
</div>
);
};
export default ActivityTable;
It looks like you're using activity as a prop inside ActivityTable, but never actually supplying that prop.
<ActivityTable activity={foo} />
I can't tell what data you're trying to pass to the table. You're importing the context successfully in both components, but never using the context data.
I am trying to use React context as a state manager in my React Native app.
Here's the context:
import React, { createContext, useState, useEffect } from "react";
import axios from "axios";
export const GlobalContext = createContext();
export const Provider = ({ children }) => {
const [tracksList, setTracksList] = useState([
{
track_list: []
}
]);
useEffect(() => {
axios
.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?page=1&page_size=10&country=us&f_has_lyrics=1&apikey=${
process.env.REACT_APP_MM_KEY
}`
)
.then(res => {
setTracksList([
{
track_list: res.data.message.body.track_list
}
]);
})
.catch(err => console.log(err));
}, []);
return (
<GlobalContext.Provider value={[tracksList, setTracksList]}>
{children}
</GlobalContext.Provider>
);
};
export const Consumer = GlobalContext.Consumer;
Child component. Here I'd like to make an API call to get users and set this users field to global context. I can get context value from consumer, but how to set the new one?
import React, { useContext } from "react";
import { GlobalContext } from "../../context/context";
const Demo = () => {
const contextValue = useContext(GlobalContext);
console.log(contextValue, "Context outside from JSX");
return <div>Content</div>;
};
export default Demo;
So, is it possible to add new value to React context from every child component, like in Redux? Thanks in advance!
You could use the useReducer effect to achieve Redux reducers:
// Create context
export const ApiContext = React.createContext();
// Create some reducer function
const reducer = (state, action) => {
if (action.type === 'some action name') {
return {
...state,
report: action.payload,
};
}
return state;
};
// Overwrite a context provider
const Provider = ({ children }) => {
const [state, dispatch] = React.useReducer(reducer, {});
return (
<ApiContext.Provider
value={{
...state,
dispatch,
}}
>
{children}
</ApiContext.Provider>
);
};
Then you could use in components as follows:
const Component = () => {
const { dispatch, report } = React.useContext(ApiContext);
React.useEffect(() => {
const asyncPost = async () => {
const response = await fetch('some endpoint', {
method: 'POST',
});
const payload = await response.json();
// This will call a reducer action and update a state
dispatch({
type: 'some action name',
payload,
});
}
}, []);
...
};
So when Component is mounted, the state would be an empty object. Then when you update the state using the some action name action, the state becomes { report: some data from fetch }.