Created
December 24, 2019 14:54
-
-
Save rajibahmed/381d9f491eb8cc64a1b907a595e00523 to your computer and use it in GitHub Desktop.
SAP with all react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, useContext, useReducer } from "react"; | |
const api = "https://randomuser.me/api/?results=2"; | |
const NEXT_PAGE = "NEXT_PAGE"; | |
const ThemeContext = React.createContext(null); | |
const Users = ({ users, children }) => { | |
const themeCxt = useContext(ThemeContext); | |
return users.map(user => { | |
return ( | |
<div> | |
<h1>{user.name.first}</h1> | |
<div>{user.gender}</div> | |
<img src={user.picture.medium} alt="" srcset="" /> | |
<h4>{themeCxt.theme}</h4> | |
{children} | |
</div> | |
); | |
}); | |
}; | |
const navigationReducer = (state, action) => { | |
if (action.type === NEXT_PAGE) { | |
return { number: state.number + 1 }; | |
} | |
return state; | |
}; | |
const initialState = { number: 1 }; | |
const withUsers = WrappedComponent => props => { | |
const [users, setUsers] = useState([]); | |
const [page, dispatch] = useReducer(navigationReducer, initialState); | |
useEffect(() => { | |
const url = api + "&page=" + page.number; | |
fetch(url) | |
.then(res => res.json()) | |
.then(data => setUsers(data.results)); | |
}, [page]); | |
return ( | |
<> | |
<WrappedComponent users={users} {...props} /> | |
<button onClick={() => dispatch({ type: NEXT_PAGE })}> next </button> | |
</> | |
); | |
}; | |
const UserList = withUsers(Users); | |
const App = () => ( | |
<ThemeContext.Provider value={{ theme: "dark" }}> | |
<UserList /> | |
</ThemeContext.Provider> | |
); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment