redux search value

This commit is contained in:
VividTruthKeeper 2023-02-16 16:16:59 +05:00
parent 634f2b3b75
commit 0b81bcabea
5 changed files with 58 additions and 4 deletions

7
src/actions/setSearch.ts Normal file
View File

@ -0,0 +1,7 @@
// Types
import { ISearchData, ISearchDataAction } from "../types/store.types";
export const setSearch = (value: ISearchData["value"]): ISearchDataAction => ({
type: "SET_SEARCH",
payload: value,
});

View File

@ -1,6 +1,6 @@
// Modules
import { useState } from "react";
import { motion } from "framer-motion";
import { useSelector, useDispatch } from "react-redux";
// Animations
import { searchMotion } from "../../animations/search.animation";
@ -8,8 +8,22 @@ import { searchMotion } from "../../animations/search.animation";
// Icons
import { ReactComponent as Loop } from "../../assets/icons/loop.svg";
// Types
import { RootState } from "../../types/store.types";
// Actions
import { setSearch } from "../../actions/setSearch";
const Search = () => {
const [input, setInput] = useState<string>("");
const onInputChange = (value: string) => {
dispatch(setSearch(value));
};
// redux
const dispatch = useDispatch();
const inputValue = useSelector<RootState, RootState["search"]["value"]>(
(state) => state.search.value
);
return (
<form
className="search"
@ -19,13 +33,14 @@ const Search = () => {
>
<input
type="text"
value={inputValue}
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setInput(event.target.value)
onInputChange(event.target.value)
}
/>
<motion.div
initial={"rest"}
animate={input.length > 0 ? "active" : "rest"}
animate={inputValue.length > 0 ? "active" : "rest"}
variants={searchMotion}
>
<Loop />

View File

@ -0,0 +1,20 @@
// Types
import { ISearchData, ISearchDataAction } from "../types/store.types";
const initialState: ISearchData = {
value: "",
};
export const searchReducer = (
state: ISearchData = initialState,
action: ISearchDataAction
) => {
switch (action.type) {
case "SET_SEARCH": {
return { value: action.payload };
}
default: {
return state;
}
}
};

View File

@ -5,12 +5,14 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { activeLinkReducer } from "../reducers/activeLink.reducer";
import { languageReducer } from "../reducers/language.reducer";
import { newsScrollReducer, postReducer } from "../reducers/dataReducer";
import { searchReducer } from "../reducers/searchReducer";
export const allReducers = combineReducers({
activeLink: activeLinkReducer,
language: languageReducer,
newsScroll: newsScrollReducer,
post: postReducer,
search: searchReducer,
});
export const functionalityStore = configureStore({

View File

@ -46,6 +46,16 @@ export interface IPostDataAction {
payload: IPostData["data"];
}
//
export interface ISearchData {
value: string;
}
export interface ISearchDataAction {
type: "SET_SEARCH";
payload: ISearchData["value"];
}
// ALL TYPES BEFORE THIS LINE ==================
export type RootState = ReturnType<typeof allReducers>;