Skip to content

Instantly share code, notes, and snippets.

@alic-xc
Created December 6, 2022 18:28
Show Gist options
  • Save alic-xc/ba03aa79c917e33301435a3d65f34478 to your computer and use it in GitHub Desktop.
Save alic-xc/ba03aa79c917e33301435a3d65f34478 to your computer and use it in GitHub Desktop.
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
// This variable handles request header informations
const weatherAPIHeader = { "content-type": "application/json" };
// Base URL
const baseUrl = "https://weather.com";
const createRequest = (url) => ({ url, headers: weatherAPIHeader });
export const weatherAPI = createApi({
// An API Slice to connect to a particular service
reducerPath: "weatherAPI",
baseQuery: fetchBaseQuery({ baseUrl }),
endpoints: (builder) => ({
getCurrentWeather: builder.query({
// Get request to get current weather (no params)
query: () => createRequest(`/weather/`),
}),
getWeatherForecastRange: builder.query({
// Get request to get weather forecast range (with params)
query: (params) =>
createRequest(
`/weather/?from_date=${params.fromDate}&to_date=${params.toDate}`
),
}),
sendWeatherData: builder.mutation({
// Post request to post data
query: (data) => ({
url: "weather/",
method: "POST",
body: data,
}),
}),
}),
});
export const { useGetCurrentWeatherQuery, useGetWeatherForecastRangeQuery, useSendWeatherDatautation } = weatherAPI;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment