score:0
You can write a Issues context provider that will provide {issues,useIssues}
where issues are the issues and useIssues is a function that takes {user,repo}
.
export const Issues = React.createContext();
export default ({ children }) => {
const [issues, setIssues] = useState([]);
const useIssues = ({ user, repo }) => {
useEffect(() => {
axios
.get(
`https://api.github.com/repos/${user}/${repo}/issues`
)
.then(response => {
setIssues(response.data);
})
.catch(err => console.log(err));
}, [user, repo]);
return issues;
};
return (
<Issues.Provider value={{ issues, useIssues }}>
{children}
</Issues.Provider>
);
};
The component that has all the components that need issues can import this issues provider:
import IssuesProvider from './IssuesProvider';
export default () => (
<IssuesProvider>
<ComponentThatNeedsIssues />
<ComponentThatSetsAndGetsIssues />
</IssuesProvider>
);
For a component that needs to set issues you can get useIssues from context:
const { useIssues } = useContext(Issues);
const issues = useIssues({user,repo});
For a component that only needs issues:
const { issues } = useContext(Issues);
To see it all work together there is a codepen here
score:2
You are right by saying you need React.Context
to handle this situation.
- You need to wrap your components into this context.
import React from "react";
const IssuesStateContext = React.createContext();
const IssuesDispatchContext = React.createContext();
function issuesReducer(state, action) {
switch (action.type) {
case "setIssues": {
return [...action.payload];
}
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
}
function IssuesProvider({ children }) {
const [state, dispatch] = React.useReducer(issuesReducer, []);
return (
<IssuesStateContext.Provider value={state}>
<IssuesDispatchContext.Provider value={dispatch}>
{children}
</IssuesDispatchContext.Provider>
</IssuesStateContext.Provider>
);
}
function useIssuesState() {
const context = React.useContext(IssuesStateContext);
if (context === undefined) {
throw new Error("useIssuesState must be used within a IssuesProvider");
}
return context;
}
function useIssuesDispatch() {
const context = React.useContext(IssuesDispatchContext);
if (context === undefined) {
throw new Error("useIssuesDispatch must be used within a IssuesProvider");
}
return context;
}
export { IssuesProvider, useIssuesState, useIssuesDispatch };
By using this separation in context you will be able to set issues coming from github in one component and render them in a completely different one.
Example:
App.js
ReactDOM.render(
<IssuesProvider>
<Component1 />
<Component2 />
</IssuesProvider>
)
Component 1
import React from 'react'
import { useIssuesDispatch } from './issues-context'
function Component1() {
const dispatch = useIssuesDispatch()
// fetch issues
// .then dispatch({ type: 'setIssues', payload: response })
// render
}
Component 2
import React from 'react'
import { useIssuesState } from './issues-context'
function Component2() {
const issues = useIssuesState()
// if issues.length > 0 ? render : null
}
Source: stackoverflow.com
Related Query
- How to combine custom hook for data fetching and context?
- How to GET data in a custom hook and dispatch it to context
- How to pass data into useState using useEffect - next.js ( swr hook for fetching and cache )
- How to do Server Side Rendering in React With React Loadable and Fetching Data for Components (Like Next.js)?
- REACT: How to create a reusable custom hook with functions and effects that can change & react to changes in a host component's data
- How to fetch data from a custom React hook (API) with onClick and display it in a Div using TypeScript?
- react (next) wait context data and passing values to custom hook
- How to extract text input value and pass down that value down to a child component as a prop to use for fetching third part api data in React?
- Can't perform a React state update on an unmounted component when using custom hook for fetching data
- Problem with custom ContextProvider state when using custom hook for fetching data in multiple tables in React
- How to set initial state for useState Hook in jest and enzyme?
- How to write a custom schema validation using yup.addMethod() for country name and code?
- How do I send custom data in react-router goBack method like push and replace methods?
- How to fetch data and store in React Context API?
- How do I set custom fonts for header, body, and button tags for Material UI?
- How to logically combine react-router and redux for client- and server-side rendering
- How can I mock return data from a custom hook in React/Jest?
- How to set initial state value for useState Hook in jest and enzyme?
- How do I map values for custom thumbnails using react-responsive-carousel and react-image-magnifiers?
- Testing a custom context hook that uses a useEffect hook and apollo
- How to render only the concerned component with a custom hook and useContext
- How to hide and show progress bar when fetching data from network?
- How can i get array of object from this data for state and count in reactjs
- How to combine custom hooks and selector results?
- How to fix my React Context to render useEffect and reload table data
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- When and how to fetch data for detail view in react/router/redux app?
- How Do I Pass a Function Through A React Component For Data Sharing Between Parent and Child?
- Custom onChange for React Hook Form and watch()
- How to render custom elements for each item in an object (Map data structure) in React TS?
More Query from same tag
- React - Return an object to pass through props
- How to do both inclusive and exclusive routing?
- Is there a way to apply CSS styling to lazy-loaded images before they fully load with Gatsby and Sharp?
- reactjs a onclick bind error , what can ı do?
- Barebones React app instanciates App and calls render twice
- Order date in React
- How to store images securely and allow access only for user [React]
- How to do slow scrolling like these website are doing
- Use React-Hook with redirect and setTimeout
- bootstrap placing item in middle
- How can I bold a part of a text in React.js?
- How to use the upload control from ant design, to get a reference of the file
- Change folder of "next export"
- .reduce in lodash fucntionality
- Dynamically Open and Close antd / react Collapse Component
- how can i add setinterval function inside React new array state
- trigger on the buttons in the slider slick
- Is there any way to change image within a time period in react JS
- Apollo GraphQL Caching Questions (cacheRedirects and readFragment)
- Bootstrap's toggle button group not calling onChange event in react
- ReactCSSTransitionGroup with CSS Modules
- I need to use Mongoose to search with non-overlapping parameters?
- When to use useEffect with no deps?
- React JS Error after requiring ReactRouter - Warning: React.createElement: type should not be null, undefined, boolean, or number
- Error when running jest on a react native + typescript app (Jest encountered an unexpected token)
- Query API with Array Parameters in React
- Component doesn't re-render when store updates - Mobx
- Not able to type in Input field in React.js. Why?
- Shopify Polaris Page tag not working - Rails and reactJS
- Cannot unit test useClickAway with ReactTestUtils