Created
April 30, 2021 20:26
-
-
Save salmanx/0a681b4309e6035d6c499be8cc89721d to your computer and use it in GitHub Desktop.
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
// basic uses | |
// user component using useState | |
const User = () => { | |
const [userDetails, setUserdetails] = useState(); | |
const [loading, setLoading] = useState(false); | |
const [error, setError] = useState(); | |
useEffect(() => { | |
setLoading(true); | |
const getUsers = async () => { | |
let response = await axios.get('/users'); | |
if (response.status == 200) { | |
setUserdetails(response.data); | |
setError(false); | |
return; | |
} | |
setError(response.error); | |
}; | |
getUsers(); | |
setLoading(false); | |
}); | |
return ( | |
<div> | |
{loading ? ( | |
<p>loading...</p> | |
) : error ? ( | |
<p>{error}</p> | |
) : ( | |
<ul> | |
{userDetails.map((user) => ( | |
<li key={user.id}> | |
<h1>{user.name}</h1> | |
<p>{user.location}</p> | |
</li> | |
))} | |
</ul> | |
)} | |
</div> | |
); | |
}; | |
export default User; |
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
const ACTIONS = { | |
CALL_API: 'call-api', | |
SUCCESS: 'success', | |
ERROR: 'error', | |
}; | |
const userDetailsReducer = (state, action) => { | |
switch (action.type) { | |
case ACTIONS.CALL_API: { | |
return { | |
...state, | |
loading: true, | |
}; | |
} | |
case ACTIONS.SUCCESS: { | |
return { | |
...state, | |
loading: false, | |
userDetails: action.data, | |
}; | |
} | |
case ACTIONS.ERROR: { | |
return { | |
...state, | |
loading: false, | |
error: action.error, | |
}; | |
} | |
} | |
}; | |
const initialState = { | |
userDetails: '', | |
loading: false, | |
error: null, | |
}; | |
const User = () => { | |
const [state, dispatch] = useReducer(userDetailsReducer, initialState); | |
const { userDetails, loading, error } = state; | |
useEffect(() => { | |
dispatch({ type: ACTIONS.CALL_API }); | |
const getUsers = async () => { | |
let response = await axios.get('/users'); | |
if (response.status == 200) { | |
dispatch({ type: ACTIONS.SUCCESS, data: response.data }); | |
return; | |
} | |
dispatch({ type: ACTIONS.ERROR, error: response.error }); | |
}; | |
getUsers(); | |
}); | |
return ( | |
<div> | |
{loading ? ( | |
<p>loading...</p> | |
) : error ? ( | |
<p>{error}</p> | |
) : ( | |
<ul> | |
{userDetails.map((user) => ( | |
<li key={user.id}> | |
<h1>{user.name}</h1> | |
<p>{user.location}</p> | |
</li> | |
))} | |
</ul> | |
)} | |
</div> | |
); | |
}; | |
export default User; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment