Skip to content

Instantly share code, notes, and snippets.

@rajibahmed
Created December 24, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajibahmed/381d9f491eb8cc64a1b907a595e00523 to your computer and use it in GitHub Desktop.
Save rajibahmed/381d9f491eb8cc64a1b907a595e00523 to your computer and use it in GitHub Desktop.
SAP with all react hooks
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