-1

I'm trying to use the useReducer hook to fetch data from an API and then update state. Since this is a small project, I'm trying to avoid using useContext, and instead just passing the dispatch function down as props.

How I've done it before is using a normal reducer for manipulating state, and an asyncReducer for fetching data, however I can't figure out how to use the two together. Would appreciate any guidance. I'll supply a link to the full code below. Just visit the repo and hit the period key (.) to view it. Main files to look at are App.js, reducer.js and letters.jsx

[]https://github.com/robert-levy/cocktail-finder

robert theboss
  • 101
  • 4
  • 13
  • I'm not quite sure what you mean by making a reducer async. – Dan Zuzevich Sep 18 '21 at 16:51
  • A reducer is not meant to have any logic that requires fetching data. – Dan Zuzevich Sep 18 '21 at 16:54
  • Here's a part of a project I worked on before which used a async reducer to make api calls, and then a second reducer to manipulate state. I want to try do something similar. https://www.codepile.net/pile/vg4WNOe2 – robert theboss Sep 18 '21 at 17:00
  • Not sure if any other people can weigh in here, but I'm not sure this is a pattern you want to follow. I've never heard of it. Maybe it's because I'm used to Redux, where your async api calls are handled via actions, completely separate from the reducers. Perhaps I am wrong though. – Dan Zuzevich Sep 18 '21 at 17:09
  • I haven't really seen this pattern either, but I was shown it while on a React course provided by my workplace. I'm open to any other ways of doing it, but would prefer to avoid the use of other packages e.g. Redux – robert theboss Sep 18 '21 at 17:19
  • I posted a solution. Not sure if that will work, hopefully it does. – Dan Zuzevich Sep 18 '21 at 17:34

1 Answers1

1

From checking out the code from your prior application, I'm not positive this will work, but let's see. Change whatever you need to reflect what I have here.

import { reducer, asyncReducer initialState } from './state/reducer'

const App = () => {

  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div className="App">
      <NavigationBar />
      <Container>
        <Row>
          <Letters dispatch={asyncReducer(dispatch)} />
        </Row>
        <Row className="justify-content-center">
          <SearchBar />
        </Row>
        <Row>
          <Cocktails />
        </Row>
      </Container>
    </div >
  );
}
Dan Zuzevich
  • 3,651
  • 3
  • 26
  • 39