skip to Main Content

I am creating react app based on store and react redux which fetch data from json file. And I have a problem, I created all structure and it’s showing properly but when I try to edit some data it shows me error: state.properties.map is not a function
I don’t have full understanding how store and redux exactly work, thats why I need your help to find where is a problem, could you help me?

Reducer:

import { UPDATE_PROPERTY } from "./actions";
import data from "./data.json"; // Importuj dane z pliku data.json

const initialState = {
  properties: data, // Ustaw dane z data.json jako początkowy stan properties
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case UPDATE_PROPERTY:
      const updatedProperties = state.properties.map((prop) =>
        prop.name === action.payload.name ? action.payload : prop
      );
      return { ...state, properties: updatedProperties };
    default:
      return state;
  }
};

export default rootReducer;

Store:

import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";

const store = configureStore({
  reducer: {
    data: rootReducer,
  },
});

export default store;

Actions:

export const UPDATE_PROPERTY = 'UPDATE_PROPERTY';

export const updateProperty = (property) => ({
  type: UPDATE_PROPERTY,
  payload: property,
});

Index.js:

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import App from "./App";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

Property:

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import TextField from "@material-ui/core/TextField";
import Checkbox from "@material-ui/core/Checkbox";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Autocomplete from "@material-ui/lab/Autocomplete";

import { updateProperty } from "./actions";

const Property = ({ property }) => {
  const dispatch = useDispatch();
  const [editedProperty, setEditedProperty] = useState(property);

  const handleBlur = () => {
    dispatch(updateProperty(editedProperty));
  };

  const handleChange = (event) => {
    const { name, value, type, checked } = event.target;
    const newValue = type === "checkbox" ? checked : value;

    setEditedProperty({
      ...editedProperty,
      [name]: newValue,
    });
  };

  return (
    <div>
      <h3>{property.name}</h3>
      {property.type === "text" && (
        <TextField
          name="value"
          value={editedProperty.value}
          onBlur={handleBlur}
          onChange={handleChange}
        />
      )}
      {property.type === "checkbox" && (
        <FormControlLabel
          control={
            <Checkbox
              name="value"
              checked={editedProperty.value}
              onBlur={handleBlur}
              onChange={handleChange}
            />
          }
          label="Check"
        />
      )}
      {property.type === "combobox" && (
        <Autocomplete
          options={property.options}
          name="value"
          value={editedProperty.value}
          onBlur={handleBlur}
          onChange={(event, newValue) => {
            handleChange({ target: { name: "value", value: newValue } });
          }}
          freeSolo
          renderInput={(params) => <TextField {...params} />}
        />
      )}
    </div>
  );
};

export default Property;

App:

import React from "react";
import { useSelector } from "react-redux";
import Property from "./Property";
import Accordion from "@mui/material/Accordion";
import AccordionSummary from "@mui/material/AccordionSummary";
import AccordionDetails from "@mui/material/AccordionDetails";
 function App() {
  const properties = useSelector((state) => state.data.properties);

  const groupedProperties = {};

  properties.properties.forEach((property) => {
    if (!groupedProperties[property.group]) {
      groupedProperties[property.group] = [];
    }
    groupedProperties[property.group].push(property);
  });

  return (
    <div className="App">
      {Object.entries(groupedProperties).map(([groupName, groupProperties]) => (
        <Accordion key={groupName}>
          <AccordionSummary>{groupName}</AccordionSummary>
          <AccordionDetails>
            <div>
              {groupProperties.map((property) => (
                <Property key={property.name} property={property} />
              ))}
            </div>
          </AccordionDetails>
        </Accordion>
      ))}
    </div>
  );
}

export default App;

Thats all components I use, If you see (as propably will be) some bad practice I do or stupid solutions – I will be grateful if you point them out.

2

Answers


  1. Chosen as BEST ANSWER

    Do someone have another solution?


  2. By default properties is undefined. .map cannot work with undefined.

    Try to use this

    const updatedProperties = state.properties ? state.properties.map((prop) =>
      prop.name === action.payload.name ? action.payload : prop
    ) : [];
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search