DEV Community

Cover image for Using React/Redux with a Golang Backend
Nik L.
Nik L.

Posted on

Using React/Redux with a Golang Backend

Building a full-stack application involves combining powerful frontend technologies like React and Redux with a robust backend implemented in Golang. In this guide, we'll explore the integration of these technologies, emphasizing a RESTful communication style for seamless data exchange between the frontend and backend.

Prerequisites

Before you begin, ensure you have the necessary tools installed:

  • Node.js and npm for React development
  • Golang for backend development

Building the React Frontend

Creating a React App

To kickstart your React project, use the following commands to create and navigate into your app's directory:

npx create-react-app my-react-app
cd my-react-app
Enter fullscreen mode Exit fullscreen mode

Installing Dependencies

Install the essential dependencies, including Redux and React-Redux:

npm install redux react-redux
Enter fullscreen mode Exit fullscreen mode

Implementing Redux for State Management

Crafting Actions

Actions define the operations that trigger state changes in your Redux store. The following fetchData action demonstrates how to fetch data from a backend API:

// actions.js
export const fetchData = () => {
  return async (dispatch) => {
    try {
      const response = await fetch('http://your-api-url/data');
      const data = await response.json();
      dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
    } catch (error) {
      dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
    }
  };
};
Enter fullscreen mode Exit fullscreen mode

Constructing Reducers

Reducers specify how the application's state changes in response to actions. The dataReducer handles the state changes for fetching data:

// reducers.js
const initialState = {
  data: [],
  error: null,
};

const dataReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_DATA_SUCCESS':
      return { ...state, data: action.payload, error: null };
    case 'FETCH_DATA_FAILURE':
      return { ...state, error: action.payload };
    default:
      return state;
  }
};

export default dataReducer;
Enter fullscreen mode Exit fullscreen mode

Integrating Redux in the App

Integrate Redux into your React app by connecting it through react-redux and dispatching the fetchData action:

// App.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from './actions';

const App = () => {
  const dispatch = useDispatch();
  const data = useSelector((state) => state.data);

  useEffect(() => {
    dispatch(fetchData());
  }, [dispatch]);

  return (
    <div>
      {/* Display data in the component */}
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Developing a Golang Backend

Setting Up a Golang Server

Set up a basic Golang server to handle requests. This example serves data for a weather API:

// main.go
package main

import (
    "encoding/json"
    "net/http"
)

type Data struct {
    Temperature int    `json:"temperature"`
    Forecast    string `json:"forecast"`
}

func main() {
    http.HandleFunc("/data", getData)
    http.ListenAndServe(":8080", nil)
}

func getData(w http.ResponseWriter, r *http.Request) {
    // Simulate data retrieval from a database
    data := Data{
        Temperature: -6,
        Forecast:    "cloudy",
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(data)
}
Enter fullscreen mode Exit fullscreen mode

Testing the Integrated Application

  1. Start the Golang server:
go run main.go
Enter fullscreen mode Exit fullscreen mode
  1. Start the React app:
npm start
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser to witness the seamless interaction between the React frontend and Golang backend.

Conclusion

This guide has provided a step-by-step walkthrough of integrating React/Redux with a Golang backend, emphasizing RESTful communication. By combining these technologies, you can build flexible and powerful full-stack applications. Feel free to explore and adapt these concepts in your projects. Happy coding!

Top comments (0)