moosespirit94
moosespirit94

Reputation: 99

How to make this into a function

I have this redux hook. I will essentially be creating fetchStudents for student, district, school, etc. Instead of rewriting this code, I essentially want to be able to pass in the URL and the type. How can I do this?

import fetch from 'isomorphic-fetch';
import { createAction } from 'utils/actionUtils';
import * as types from './StudentConstants';

export const setLoading = createAction(types.SET_LOADING);

const getStudents = students => ({
  type: types.SET_STUDENTS,
  payload: students,
});

export const fetchStudents = (students) => {
  return (dispatch) => {
    return fetch('http://gsndev.com/gsndb/student/', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        Authorization: `JWT ${localStorage.token}`,
      },
    })
      .then(response => response.json())
      .then((s) => {
        dispatch(getStudents(s));
      })
      .catch(error => (error));
  };
};

Upvotes: 1

Views: 48

Answers (1)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

fetchStudents is normal function. So pass any arguments you want and use these arguments for branching logic.

For example

export const fetchStudents = (type, url) => {
    return (dispatch) => {
        return fetch(url, {   // Here you may put url
            method: 'GET',
            headers: {
                Accept: 'application/json',
                Authorization: `JWT ${localStorage.token}`,
            },
        })
        .then(response => response.json())
        .then((s) => {
            switch (type) {
                case 'students':
                    dispatch(getStudents(s));
                    break;
                case 'district':
                    dispatch(getDistricts(s));  // There can be action creator for districts
                    break;
                // And so on for other types
            }
        })
        .catch(error => (error));
    };
};

Upvotes: 1

Related Questions