Categories
React Answers

How to fix the Redux store does not have a valid reducer error in React?

Sometimes, we want to fix the Redux store does not have a valid reducer error in React.

In this article, we’ll look at how to fix the Redux store does not have a valid reducer error in React.

How to fix the Redux store does not have a valid reducer error in React?

To fix the Redux store does not have a valid reducer error in React, we can call combineReducer with an object that has the state property name as keys and the corresponding reducer as the values.

For instance, we write:

import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import { combineReducers, createStore } from "redux";

const CountReducer = (state = 0, action) => {
  switch (action.type) {
    case "ADD":
      return state + 1;
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  count: CountReducer
});

const store = createStore(rootReducer);

const Counter = () => {
  const count = useSelector((s) => s.count);
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch({ type: "ADD" })}>+</button>
      <span>{count}</span>
    </div>
  );
};

export default function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

We have the CountReducer reducer function that returns the state + 1 if the 'ADD' action type is dispatched.

Then we call combineReducers with an object with the count as the state property name and the CounterReducer as its reducer.

Next, we call createStore with rootReducer to create the store from the root reducer.

Then we create the Counter component that calls the useSelector hook to return the the value of the count state.

And we call the useDispatch hook to return the dispatch function that we can use to dispatch actions.

Finally, in App, we wrap Provider around Counter so useSelector and useDispatch can be used in Counter.

And we set the store prop to the store so we can dispatch actions and get states from the store.

Conclusion

To fix the Redux store does not have a valid reducer error in React, we can call combineReducer with an object that has the state property name as keys and the corresponding reducer as the values.

Categories
JavaScript Answers

How to disable browser cache with JavaScript Axios?

Sometimes, we want to disable browser cache with JavaScript Axios.

In this article, we’ll look at how to disable browser cache with JavaScript Axios.

How to disable browser cache with JavaScript Axios?

To disable browser cache with JavaScript Axios, we can set the Cache-control and Pragma request headers to no-cache.

And we set the Expires request header to 0.

For instance, we write:

axios.defaults.headers = {
  'Cache-Control': 'no-cache',
  'Pragma': 'no-cache',
  'Expires': '0',
};

(async () => {
  const {
    data
  } = await axios.get('https://catfact.ninja/fact')
  console.log(data)
})()

We set axios.defaults.headers to:

{
  'Cache-Control': 'no-cache',
  'Pragma': 'no-cache',
  'Expires': '0',
}

to disable caching the response.

Then we call axios.get to make the GET request to the URL we want.

Conclusion

To disable browser cache with JavaScript Axios, we can set the Cache-control and Pragma request headers to no-cache.

And we set the Expires request header to 0.

Categories
React Answers

How to add export to CSV button in a React table?

Sometimes, we want to add export to CSV button in a React table.

In this article, we’ll look at how to add export to CSV button in a React table.

How to add export to CSV button in a React table?

To add export to CSV button in a React table, we can use the react-csv library.

To install it, we run:

npm i react-csv

Then we add the button to the table by writing:

import React from "react";
import { useTable } from "react-table";
import { CSVLink } from "react-csv";

const csvData = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Doe" }
];

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => {
    return csvData.map((d) => Object.values(d));
  }, []);

  return (
    <>
      <CSVLink data={data}>Download me</CSVLink>
      <Table columns={columns} data={csvData} />;
    </>
  );
}

We create the Table component which calls the useTable hook with the columns and data props to return an object that has the properties we use to create the table.

Next, we add a CSV download link by using the CSVLink component.

We pass in a nested array as the value of the data prop so react-csv can generate the CSV from it.

We create the nested array by calling useMemo with a callback that returns the nested array which we create by calling csvData.map with a callback that returns the values in an array from each csvData entry with Object.values.

Now we should see a Download me button which we can click to download the CSV.

Conclusion

To add export to CSV button in a React table, we can use the react-csv library.

Categories
React Answers

How to create a dynamic drop down list with React Bootstrap?

Sometimes, we want to create a dynamic drop down list with React Bootstrap.

In this article, we’ll look at how to create a dynamic drop down list with React Bootstrap.

How to create a dynamic drop down list with React Bootstrap?

To create a dynamic drop down list with React Bootstrap, we can call the option array’s map method to return the option element for each option in the array.

For instance, we write:

import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Form } from "react-bootstrap";

const options = [
  { name: "One", id: 1 },
  { name: "Two", id: 2 },
  { name: "Three", id: 3 },
  { name: "four", id: 4 }
];

export default function App() {
  const [val, setVal] = useState();
  console.log(val);

  return (
    <Form.Select value={val} onChange={(e) => setVal(e.target.value)}>
      {options.map((o) => {
        const { name, id } = o;
        return <option value={id}>{name}</option>;
      })}
    </Form.Select>
  );
}

We call options.map with a callback that returns the option element by setting the value prop to id and the text content to name.

Now we should see the options One, Two, Three and Four available in the drop down.

We also set the value prop of Form.Select to val and the onChange prop to a function that calls setVal with e.target.value to set val to the selected option’s value attribute value.

Conclusion

To create a dynamic drop down list with React Bootstrap, we can call the option array’s map method to return the option element for each option in the array.

Categories
React Answers

How to change the style of a button on click with React?

Sometimes, we want to change the style of a button on click with React.

In this article, we’ll look at how to change the style of a button on click with React.

How to change the style of a button on click with React?

To change the style of a button on click with React, we can set the className prop to an object with styles controlled by states.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [cls, setCls] = useState("green");

  return (
    <>
      <style>{`
        .red {color: red}
        .green {color: green}
      `}</style>
      <button
        className={cls}
        onClick={() => setCls((cls) => (cls === "red" ? "green" : "red"))}
      >
        Button
      </button>
    </>
  );
}

We have the red and green classes with the color CSS property set to red and green respectively.

Then we set the className prop to the cls state to let us control which class to set the button to.

Next, we set the onClick prop to a function that calls setCls with a function that returns the class we want to set for the button.

As a result, when we click the button, we see the text of the button toggle between green and red.

Conclusion

To change the style of a button on click with React, we can set the className prop to an object with styles controlled by states.