I\'am trying to fetch some data with new react useReducer API and stuck on stage where i need to fetch it async. I just don\'t know how :/
How to place data fetching
You can use the useAsync package: https://github.com/sonofjavascript/use-async, which basically is an extension of the useReducer hook that allows managing asynchronous actions over application's state through http requests.
Set the client agent (you can use your own http client) through the ClientStore:
import React from 'react'
import { ClientStore } from '@sonofjs/use-async'
import axios from 'axios'
import Component from './Component.jsx'
const ViewContainer = () => (
)
export default ViewContainer
Define and use your actions:
import React, { useEffect } from 'react'
import useAsync from '@sonofjs/use-async'
const actions = {
FETCH_DATA: (state) => ({
...state,
loading: true,
request: {
method: 'GET',
url: '/api/data'
}
}),
FETCH_DATA_SUCCESS: (state, response) => ({
...state,
loading: false,
data: response
}),
FETCH_DATA_ERROR: (state, error) => ({
...state,
loading: false,
error
})
}
const initialState = {
loading: false,
data: {}
}
const Component = () => {
const [state, dispatch] = useAsync(actions, initialState)
useEffect(() => {
dispatch({ type: 'DATA' })
}, [])
return (
<>
{state.loading ? Loading... : null}
{{JSON.stringify(state.data)}}
{state.error ? Error: {JSON.stringify(state.error)} : null}
<>
)
}
export default Component