I created a React app that uses Redux for controlling state and learning that has not been the best road. The app is also using Ruby on Rails for a backend API
store data in.
This app is a cookbook for storing recipes and being able to leave reviews as well as give it a rating to show how much you like each recipe.
React
Generating a React app is quite easy to start off with npx create-react-app
and start by adding components. At first it felt a little foreign then after five minutes of using it, things started to find their way into places. Files feel more like a proper structure using the React framework with being able to target files using import React from 'react'
at the top of the file. The format is used for collecting any other file that has been exported in their home file.
Rails
Setting up the Rails api was nearly just as easy with the quick command rails new CoolBackend --api
using the api flag with prevent views from being generated. Also to be noted, one should not use rails scaffold as that will generate views which ultimately will not be used for this type of application, that will be handled by React.
Redux
Redux is a library that is used to control a "global" state as it were. State is normally created in a class component and is then passed down to child components. Sending state down several child components gets to be a little tedious which leaves Redux to the rescue!
Redux allows for action creators to be called on from anywhere in the React file structure and be used to track state. This functions are imported
just the same as any other file would be collected.
A common action would like how I set up fetching all recipes:
const API = 'http://localhost:3000'
export const fetchRecipes = () => {
return dispatch => {
fetch(`${API}/recipes`)
.then(resp => resp.json())
.then(recipes => dispatch({
type: 'GET_RECIPES',
payload: recipes }))
}
}
This function has the keyword dispatch
and it used by redux-thunk which allows for AJAX requests to and from the API endpoint which works asynchronously.
With this functionality helps to keep state up to date with the rest of the app and keeps local state clean and more manageable.
Conclusion
My learning journey with React and Redux has been a fun one right after just becoming acquainted with JavaScript made for some confusing mistakes. One being how to update state when a new route has been met. For that componentDidMount()
helps for firing off a quick redux action creator to get the list of recipes when navigating to the /recipes
route.
More lifecycle methods exist along with all the React hooks I did not have time to look into look to make using React/Redux a more streamed lined affair.
Top comments (0)