header creation in http. Sample auth request to backend.

This commit is contained in:
Ruidy Nemausat 2020-04-24 15:00:54 +02:00
parent 85e8067b6c
commit 40ccfaf90f
3 changed files with 24 additions and 9 deletions

View file

@ -6,6 +6,7 @@ import {
deleteItemAsync,
getItemsAsync,
} from "../../store/itemSlice";
import { useFirebase } from "../../services/auth";
const useStyles = () => ({
removeBtn: {
@ -20,12 +21,17 @@ export default function List() {
const dispatch = useDispatch();
const styles = useStyles();
const firebase = useFirebase();
// UseEffect loads items from the db when component renders.
// Precising dependencies so it doesn't render infinitely.
useEffect(() => {
dispatch(getItemsAsync());
}, [dispatch]);
firebase.auth.onAuthStateChanged(async (user) => {
if (user) {
const token = await firebase.auth.currentUser.getIdToken();
dispatch(getItemsAsync(token));
}
});
}, [dispatch, firebase.auth]);
return (
<ListGroup>

View file

@ -0,0 +1 @@
export const makeHeaders = (token) => ({ authorization: `Bearer ${token}` });

View file

@ -1,6 +1,7 @@
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import * as URL from "../constants/urls";
import { makeHeaders } from "../services/http";
export const itemSlice = createSlice({
name: "item",
@ -29,25 +30,32 @@ export const itemSlice = createSlice({
/**
* redux-thunk which fetches Items asynchronously from db.
*/
export const getItemsAsync = () => async (dispatch) => {
export const getItemsAsync = (token) => async (dispatch) => {
dispatch(setItemsLoading);
const { data } = await axios.get(URL.ITEMS);
const { data } = await axios.get(URL.ITEMS, {
headers: makeHeaders(token),
});
dispatch(getItems(data));
};
/**
* Creates a new Item in the db.
*/
export const addItemAsync = (name) => async (dispatch) => {
const { data } = await axios.post(URL.ITEMS, { name });
export const addItemAsync = (name, token) => async (dispatch) => {
const { data } = await axios.post(
URL.ITEMS,
{ name },
{ headers: makeHeaders(token) }
);
dispatch(addItem(data));
};
/**
* Deletes Item _id from the db.
*/
export const deleteItemAsync = (id) => async (dispatch) => {
await axios.delete(`${URL.ITEMS}/${id}`);
export const deleteItemAsync = (id, token) => async (dispatch) => {
await axios.delete(`${URL.ITEMS}/${id}`, { headers: makeHeaders(token) });
dispatch(deleteItem(id));
};