kandi background
Explore Kits

redux | Predictable state container for JavaScript apps | State Container library

 by   reduxjs TypeScript Version: v4.2.0 License: Non-SPDX

 by   reduxjs TypeScript Version: v4.2.0 License: Non-SPDX

Download this library from

kandi X-RAY | redux Summary

redux is a TypeScript library typically used in User Interface, State Container, React applications. redux has no bugs, it has no vulnerabilities and it has medium support. However redux has a Non-SPDX License. You can download it from GitHub.
Redux is a predictable state container for JavaScript apps. (Not to be confused with a WordPress framework – Redux Framework). It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger. You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), and has a rich ecosystem of addons.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • redux has a medium active ecosystem.
  • It has 57862 star(s) with 15173 fork(s). There are 1350 watchers for this library.
  • There were 1 major release(s) in the last 12 months.
  • There are 39 open issues and 1906 have been closed. On average issues are closed in 51 days. There are 16 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of redux is v4.2.0
redux Support
Best in #State Container
Average in #State Container
redux Support
Best in #State Container
Average in #State Container

quality kandi Quality

  • redux has 0 bugs and 0 code smells.
redux Quality
Best in #State Container
Average in #State Container
redux Quality
Best in #State Container
Average in #State Container

securitySecurity

  • redux has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • redux code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
redux Security
Best in #State Container
Average in #State Container
redux Security
Best in #State Container
Average in #State Container

license License

  • redux has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
redux License
Best in #State Container
Average in #State Container
redux License
Best in #State Container
Average in #State Container

buildReuse

  • redux releases are available to install and integrate.
  • Installation instructions, examples and code snippets are available.
  • It has 447 lines of code, 0 functions and 192 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
redux Reuse
Best in #State Container
Average in #State Container
redux Reuse
Best in #State Container
Average in #State Container
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

redux Key Features

Predictable state container for JavaScript apps

redux Examples and Code Snippets

See all related Code Snippets

Installation

copy iconCopydownload iconDownload
npm install @reduxjs/toolkit react-redux

Basic Example

copy iconCopydownload iconDownload
import { createStore } from 'redux'

/**
 * This is a reducer - a function that takes a current state value and an
 * action object describing "what happened", and returns a new state value.
 * A reducer's function signature is: (state, action) => newState
 *
 * The Redux state should contain only plain JS objects, arrays, and primitives.
 * The root state value is usually an object.  It's important that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * You can use any conditional logic you want in a reducer. In this example,
 * we use a switch statement, but it's not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counterReducer)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// There may be additional use cases where it's helpful to subscribe as well.

store.subscribe(() => console.log(store.getState()))

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'counter/incremented' })
// {value: 1}
store.dispatch({ type: 'counter/incremented' })
// {value: 2}
store.dispatch({ type: 'counter/decremented' })
// {value: 1}

Redux Toolkit Example

copy iconCopydownload iconDownload
import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})

export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

Why items appends to the redux rather than replace?

copy iconCopydownload iconDownload
case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: action.payload.items,
                    pagination: action.payload.pagination
                }
            };

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema

copy iconCopydownload iconDownload
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:6000',
      changeOrigin: true,
    })
  );
};
"react-scripts": "5.*", 
"react-scripts": "4.0.3",
"react-scripts": "5.*", 
"react-scripts": "4.0.3",
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

The unauthenticated git protocol on port 9418 is no longer supported

copy iconCopydownload iconDownload
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
git config --global url."https://".insteadOf git://
[remote "upstream"]
    url = git://github.com/curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
[remote "upstream"]
    url = git@github.com:curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
[remote "upstream"]
    url = git://github.com/curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
[remote "upstream"]
    url = git@github.com:curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
git config --global url."https://github".insteadOf git://github
Unhandled rejection Error: Command failed: /usr/bin/git submodule update -q --init --recursive
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
fatal: remote error:
  The unauthenticated git protocol on port 9418 is no longer supported.
Please see https://github.blog/2021-09-01-improving-git-protocol-security-github/ for more information.
fatal: clone of 'git://github.com/jquery/sizzle.git' into submodule path '/root/.npm/_cacache/tmp/git-clone-19674e32/src/sizzle' failed
Failed to clone 'src/sizzle'. Retry scheduled
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
git config --global url."https://github".insteadOf git://github
Unhandled rejection Error: Command failed: /usr/bin/git submodule update -q --init --recursive
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
fatal: remote error:
  The unauthenticated git protocol on port 9418 is no longer supported.
Please see https://github.blog/2021-09-01-improving-git-protocol-security-github/ for more information.
fatal: clone of 'git://github.com/jquery/sizzle.git' into submodule path '/root/.npm/_cacache/tmp/git-clone-19674e32/src/sizzle' failed
Failed to clone 'src/sizzle'. Retry scheduled
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
    insteadOf = ssh://
    insteadOf = git://
    insteadOf = ssh://
    insteadOf = git://

How to store the result of query from createApi in a slice?

copy iconCopydownload iconDownload
const slice = createSlice({
  name: 'auth',
  initialState: { user: null, token: null } as AuthState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addMatcher(
      api.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.token = payload.token
        state.user = payload.user
      }
    )
  },
})

java.lang.NoSuchMethodError: No virtual method setSkipClientToken(Z)V in class Lcom/facebook/GraphRequest;

copy iconCopydownload iconDownload
implementation 'com.facebook.android:facebook-marketing:[4,5)'
implementation 'com.facebook.android:facebook-marketing:latest.release'
implementation 'com.facebook.android:facebook-marketing:[4,5)'
implementation 'com.facebook.android:facebook-marketing:latest.release'

expo-barcode-scanner only works once with react-native version 0.64.2 and expo 43.0.0

copy iconCopydownload iconDownload
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';

const QrcodeReader = ({navigation}) =>  {

  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return(
  <View style={styles.container}>
      <Camera
        onBarCodeScanned={(...args) => {
          const data = args[0].data;
          result = JSON.stringify(result);
          console.log(result);
          navigation.navigate('your_next_screen',{result});
          );
        }}
        barCodeScannerSettings={{
          barCodeTypes: ['qr'],
        }}
        style={{ flex: 1 }}
      />
    </View>
  );
}
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  buttonContainer: {
    flex: 1,
    backgroundColor: 'transparent',
    flexDirection: 'row',
    margin: 20,
  },
  button: {
    flex: 0.1,
    alignSelf: 'flex-end',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    color: 'white',
  },
});

export default QrcodeReader;

MUI v5 - Extending Typography variant in TypeScript creates error &quot;No overload matches this call&quot;

copy iconCopydownload iconDownload
declare module '@mui/material/Typography' {
  interface TypographyPropsVariantOverrides {
    h1Bold: true;
  }
}
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "subtitle1" | "subtitle2" | "body1" | "body2" | "caption" | "button" | "overline" | "inherit" | "h1Bold"
<Typography variant='h1Bold'
declare module '@mui/material/Typography' {
  interface TypographyPropsVariantOverrides {
    h1Bold: true;
  }
}
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "subtitle1" | "subtitle2" | "body1" | "body2" | "caption" | "button" | "overline" | "inherit" | "h1Bold"
<Typography variant='h1Bold'
declare module '@mui/material/Typography' {
  interface TypographyPropsVariantOverrides {
    h1Bold: true;
  }
}
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "subtitle1" | "subtitle2" | "body1" | "body2" | "caption" | "button" | "overline" | "inherit" | "h1Bold"
<Typography variant='h1Bold'
declare module "@mui/material/styles" {
  interface TypographyVariants {
    h1Bold: React.CSSProperties;
  }

  // allow configuration using `createTheme`
  interface TypographyVariantsOptions {
    h1Bold?: React.CSSProperties;
  }
}

// Update the Typography's variant prop options
declare module "@mui/material/Typography" {
  interface TypographyPropsVariantOverrides {
    h1Bold: true;
  }
}

Testing React Component with React Router V6

copy iconCopydownload iconDownload
declare function MemoryRouter(
  props: MemoryRouterProps
): React.ReactElement;

interface MemoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  initialEntries?: InitialEntry[];
  initialIndex?: number;
}
const AllTheProviders = ({ children }) => {
  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {children}
      </Provider>
    </ApolloProvider>
  );
};
const customRender = (ui, options) => 
  render(ui, { wrapper: AllTheProviders, ...options });
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <ComponentUnderTest />
  </MemoryRouter>
);
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <Routes>
      <Route path="/details/:theParam" element={<ComponentUnderTest />} />
    </Routes>
  </MemoryRouter>
);
declare function MemoryRouter(
  props: MemoryRouterProps
): React.ReactElement;

interface MemoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  initialEntries?: InitialEntry[];
  initialIndex?: number;
}
const AllTheProviders = ({ children }) => {
  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {children}
      </Provider>
    </ApolloProvider>
  );
};
const customRender = (ui, options) => 
  render(ui, { wrapper: AllTheProviders, ...options });
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <ComponentUnderTest />
  </MemoryRouter>
);
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <Routes>
      <Route path="/details/:theParam" element={<ComponentUnderTest />} />
    </Routes>
  </MemoryRouter>
);
declare function MemoryRouter(
  props: MemoryRouterProps
): React.ReactElement;

interface MemoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  initialEntries?: InitialEntry[];
  initialIndex?: number;
}
const AllTheProviders = ({ children }) => {
  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {children}
      </Provider>
    </ApolloProvider>
  );
};
const customRender = (ui, options) => 
  render(ui, { wrapper: AllTheProviders, ...options });
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <ComponentUnderTest />
  </MemoryRouter>
);
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <Routes>
      <Route path="/details/:theParam" element={<ComponentUnderTest />} />
    </Routes>
  </MemoryRouter>
);
declare function MemoryRouter(
  props: MemoryRouterProps
): React.ReactElement;

interface MemoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  initialEntries?: InitialEntry[];
  initialIndex?: number;
}
const AllTheProviders = ({ children }) => {
  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {children}
      </Provider>
    </ApolloProvider>
  );
};
const customRender = (ui, options) => 
  render(ui, { wrapper: AllTheProviders, ...options });
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <ComponentUnderTest />
  </MemoryRouter>
);
const { ....queries.... } = customRender(
  <MemoryRouter
    initialEntries={["Test page", "/details/url-param-the-component-needs"]}
  >
    <Routes>
      <Route path="/details/:theParam" element={<ComponentUnderTest />} />
    </Routes>
  </MemoryRouter>
);

mongoose.connect(uri, ConnectOptions) does not recognize useNewUrlParser and other options

copy iconCopydownload iconDownload
/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
export function connect(uri: string, callback: CallbackWithoutResult): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}
interface ConnectOptions extends mongodb.MongoClientOptions {
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  bufferCommands?: boolean;
  /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  dbName?: string;
  /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  user?: string;
  /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  pass?: string;
  /** Set to false to disable automatic index creation for all models associated with this connection. */
  autoIndex?: boolean;
  /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  autoCreate?: boolean;
}
/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
export function connect(uri: string, callback: CallbackWithoutResult): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}
interface ConnectOptions extends mongodb.MongoClientOptions {
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  bufferCommands?: boolean;
  /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  dbName?: string;
  /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  user?: string;
  /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  pass?: string;
  /** Set to false to disable automatic index creation for all models associated with this connection. */
  autoIndex?: boolean;
  /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  autoCreate?: boolean;
}
/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
export function connect(uri: string, callback: CallbackWithoutResult): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}
interface ConnectOptions extends mongodb.MongoClientOptions {
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  bufferCommands?: boolean;
  /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  dbName?: string;
  /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  user?: string;
  /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  pass?: string;
  /** Set to false to disable automatic index creation for all models associated with this connection. */
  autoIndex?: boolean;
  /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  autoCreate?: boolean;
}
import { ConnectionOptions, connect } from "mongoose"

type ConnectionOptionsExtend = {
  useNewUrlParser: boolean
  useUnifiedTopology: boolean
}

const options: ConnectionOptions & ConnectionOptionsExtend = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  authSource: "admin",
  useCreateIndex: true,
  useFindAndModify: false,
  user,
  pass
}

await connect(uri, options)
mongoose.connect(dbUri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
} as ConnectOptions)

React-Typescript: Module '&quot;react-router-dom&quot;' has no exported member 'RouteComponentProps'

copy iconCopydownload iconDownload
...
function handleClick() {
  history.push("/home");
}
...
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  ...
import React from 'react';
import {useParams} from 'react-router-dom';

const Component: React.FC = (): JSX.Element => {
  const params = useParams();
  return <>Link ID parameter === "{params.id}"</>;
}
...
function handleClick() {
  history.push("/home");
}
...
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  ...
import React from 'react';
import {useParams} from 'react-router-dom';

const Component: React.FC = (): JSX.Element => {
  const params = useParams();
  return <>Link ID parameter === "{params.id}"</>;
}
...
function handleClick() {
  history.push("/home");
}
...
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  ...
import React from 'react';
import {useParams} from 'react-router-dom';

const Component: React.FC = (): JSX.Element => {
  const params = useParams();
  return <>Link ID parameter === "{params.id}"</>;
}

See all related Code Snippets

Community Discussions

Trending Discussions on redux
  • Why items appends to the redux rather than replace?
  • Invalid options object. Dev Server has been initialized using an options object that does not match the API schema
  • The unauthenticated git protocol on port 9418 is no longer supported
  • How to store the result of query from createApi in a slice?
  • React Native Android crashes on enabling debug mode
  • java.lang.NoSuchMethodError: No virtual method setSkipClientToken(Z)V in class Lcom/facebook/GraphRequest;
  • expo-barcode-scanner only works once with react-native version 0.64.2 and expo 43.0.0
  • MUI v5 - Extending Typography variant in TypeScript creates error &quot;No overload matches this call&quot;
  • Testing React Component with React Router V6
  • mongoose.connect(uri, ConnectOptions) does not recognize useNewUrlParser and other options
Trending Discussions on redux

QUESTION

Why items appends to the redux rather than replace?

Asked 2022-Apr-16 at 08:11

I'm newbie to Reactjs. The problem I'm encountered:

When Article page loads in the first time, all is fine and there are 10 articles shown. When I click on the browser back button, and then I go to the Article page for the second time, the article-list will be duplicated (so, it will be 20 articles). If I do so again, it will be 30 articles and so on ..

I want to know, why the result of API call appends for the Redux and not replace? In other word, how can I clean the Redux on page load every time? The expected result is seeing always 10 item (articles) on the page Article when I open it.


Here is a simplified of the element (for navigating to the list of articles) in the main page:

import Pages from "Constants/Pages";

const Component = () => {

    const history = useHistory();
    const navigateWithToken = (page) => {
        history.push(page);
      }
    };
    
    return (
        <div className="d-flex align-items-center flex-column py-1 ">
          <div
            className="main-footer-btn-article"
            onClick={() => navigateWithToken(Pages.Articles)}
          ></div>
          <span className="main-footer-btn-text">Articles</span>
        </div>
    )
};

export const ArticlesBtn = memo(Component);

Also, here is the Article page:

import { memo, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import PostItems from "SharedComponents/PostItems";
import { getAllPosts } from "Redux/Actions";
import Pages from "Constants/Pages";

const Page = () => {
  const posts = useSelector((state) => state?.articles?.posts?.items);
  const dispatch = useDispatch();
  const { push } = useHistory();
  useEffect(() => {
    dispatch(getAllPosts());
  }, []);

  const onClickPost = (item) => {
    push({
      pathname: Pages.SingleArticle,
      state: {
        postId: item.id,
        title: item.subject,
        is_saved: item.is_saved,
      },
    });
  };

  return (
    <div className="full-height overflow-auto">
      { 
        posts?.map((item, index) => {
          return (
            <PostItems
              {...item}
              key={item.id}
              index={index}
              onClickPost={() => onClickPost(item)}
            />
          );
        })
      }
    </div>
  );
};

export default memo(Page);

Also here is the API call:

const getAllPosts = (page = 1) => {
  return async (dispatch: ReduxDispatch) => {
    //"posts?for=for_website"
    dispatch(toggleLoading(true));
    try {
      const { data } = await axios({
        method: "GET",
        url: "posts?for=for_mobile",
        params: { page: page },
      });
      const items = data?.data?.data;
      const pagination = {
        current_page: data.data.current_page,
        last_page: data.data.last_page,
      };
      dispatch(
        dispatchItemToRedux({
          type: ReducerTypes.GET_ALL_POSTS,
          payload: {
            items,
            pagination,
          },
        })
      );
    } catch (err) {
      return Promise.reject(err);
    } finally {
      dispatch(toggleLoading(false));
    }
  };
};

Also, here is the reducer:

import ReducerTypes from "Redux/Types/ReducerTypes";

const INITIAL_STATE = {
    posts: {
        items: [],
        pagination: {}
    },
    singlePost: {
        id: null,
        subject: null,
        caption: null,
        deep_link: null,
        short_link: null,
        total_comments: null,
        total_likes: null,
        total_views: null,
        created: null,
        medias: null,
        likes: [] 
    },
    postComments: []
};

function articleReducer(state = INITIAL_STATE, action) {
    switch (action.type) {
        case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: state.posts.items.concat(action.payload.items),
                    pagination: action.payload.pagination
                }
            };
        case ReducerTypes.GET_SINGLE_POST:
            return {
                ...state,
                singlePost: action.payload
            };
        case ReducerTypes.GET_POST_COMMENTS:
            return {
                ...state,
                postComments: action.payload
            };
        case ReducerTypes.GET_POST_LIKES:
            return {
                ...state,
                singlePost: {
                    ...state.singlePost,
                    likes: action.payload
                }
            };
        default:
            return state;
    };
};
export default articleReducer;

ANSWER

Answered 2022-Apr-16 at 08:11
case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: action.payload.items,
                    pagination: action.payload.pagination
                }
            };

Try omitting that .concat()

Source https://stackoverflow.com/questions/71892118

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install redux

Redux Toolkit is our official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.

Support

The Redux docs are located at https://redux.js.org:.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Share this Page

share link
Consider Popular State Container Libraries
Try Top Libraries by reduxjs
Compare State Container Libraries with Highest Support
Compare State Container Libraries with Highest Quality
Compare State Container Libraries with Highest Security
Compare State Container Libraries with Permissive License
Compare State Container Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.