Encountered two children with the same key, - material-ui

I'm working on material table in react and when I try to delete or updated my row datas then I'm monitoring this error all of times.
Update Error: react_devtools_backend.js:4012 Warning: Encountered two children with the same key, row-cc5026f5-6a53-4f91-850d-3127467a8615. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
Delete Error: Nothing happening when I Try to delete.
What's wrong with my codes?
here is Table.js
import React, { Component, useEffect, useState } from 'react';
import MaterialTable from '#material-table/core';
import axios from 'axios';
import { emplist as RoomInfo } from './data/emplist';
function App() {
const [data, setData] = useState(RoomInfo);
const columns = [
{
title: 'ID',
field: 'id',
},
{
title: 'Floor Name',
field: 'FloorName',
},
{
title: 'Building Name',
field: 'BuildingName',
},
{
title: 'Room Code',
field: 'RoomCode',
},
{
title: 'Room Name',
field: 'RoomName',
},
{
title: 'Room Area',
field: 'RoomArea',
},
{
title: 'Room Perimeter',
field: 'RoomPerimeter',
},
{
title: 'Room Height',
field: 'RoomHeight',
},
];
return (
<MaterialTable
title="Editable Preview"
columns={columns}
data={data}
editable={{
onRowAdd: (newRow) =>
new Promise((resolve, reject) => {
const updatedRows = [
...data,
{ id: Math.floor(Math.random() * 100), ...newRow },
];
setTimeout(() => {
setData(updatedRows);
resolve();
}, 2000);
}),
onRowDelete: (selectedRow) =>
new Promise((resolve, reject) => {
const index = selectedRow.tableData.id;
const updatedRows = [...data];
updatedRows.splice(index, 1);
setTimeout(() => {
setData(updatedRows);
resolve();
}, 1000);
}),
onRowUpdate: (selectedRow, oldRow) =>
new Promise((resolve, reject) => {
const index = oldRow.tableData.id;
const updatedRow = [...data];
updatedRows[index] = updatedRow;
setTimeout(() => {
setData(updatedRows);
resolve();
}, 1000);
}),
}}
options={{
actionsColumnIndex: -1,
addRowPosition: 'first',
}}
/>
);
}
export default App;
Hi everyone, I'm working on material table in react and when I try to delete or updated my row datas then I'm monitoring this error all of times.
Update Error: react_devtools_backend.js:4012 Warning: Encountered two children with the same key, row-cc5026f5-6a53-4f91-850d-3127467a8615. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
Delete Error: Nothing happening when I Try to delete.
What's wrong with my codes?

Related

Can't access Pinia changed state in Prisma API call in a Nuxt 3 app

Somehow I when I make an API call using Prisma I can access only the default state:
import dbClient from '~/server/utils';
import { useTextStore } from '~/pinia/text'
export default defineEventHandler(async (event) => {
const { id } = event.context.params
const text = useTextStore()
const updatedText = await dbClient.opus.update({
where: {
id: parseInt(id),
},
data: {
content: text.content
},
});
return {
statusCode: 200,
body: text.content
}
})
Here's the Pinia store code:
import { defineStore } from 'pinia'
export const useTextStore = defineStore({
id: 'text',
state: () => {
return {
editor:'Введите текст',
}
},
actions: {
updateText(newContent) {
this.editor = newContent
}
},
getters: {
content: state => state.editor,
},
})
The state changes are shared across components and pages but can't get through to the eventHandler. Is it Nuxt 3 or some other mistake I should look into?

Redirect is not working in Electron and React Router v6

I'm trying to build a simple app showing invoices.
When I create a new invoice, the path is invoice/new
When a change happens, I want to redirect to the newly created invoice
export const action = async ({ request, params }) => {
const newInvoice = // save the invoice
if (params.invoiceId === "new") {
return redirect(`/invoice/${newInvoiceId}`);
}
return { ok: true };
};
But it's not redirecting - it stays in /invoice/new
export const loader = async ({ params }) => {
const invoiceId = params.invoiceId;
console.log("invoiceId", invoiceId); // invoiceId always 'new' even after `redirect`
const invoice = // fetch invoice if invoiceId !== 'new'
return { invoice };
};
I don't understand why...
Here is my router
const router = createMemoryRouter(
[
{
path: "/",
element: <Root />,
children: [
{
path: "/",
element: <Home />,
loader: homeLoader,
},
],
},
{
path: "/invoice/:invoiceId",
element: <Invoice />,
loader: invoiceLoader,
action: invoiceAction,
},
{
path: "/client/:clientId",
element: <Client />,
loader: clientLoader,
action: clientAction,
},
],
{
initialEntries: ["/", "/invoice/new"],
},
);
I can give more clue if needed, of course

redux-toolkit InitialState not changing

My problem is that initialState from slice.js not changing, when I console.log store(using UseSelector) I see that state.list empty and did not changed.I'm trying to catch data from GET endpoint, endpoint is working.
store.js
import { configureStore } from '#reduxjs/toolkit';
import shopReducer from '../connection/shopSlice';
export const store = configureStore({
reducer: {
shop: shopReducer,
},
devTools: true
});
slice.js
import { createAsyncThunk, createSlice } from '#reduxjs/toolkit';
import axios from 'axios';
export const getProducts = createAsyncThunk(
'shop/getProducts',
async () => {
const response = await axios.get('http://localhost:3000/products');
return response.data;
}
);
export const listOfProducts = createSlice({
name: 'shop',
initialState: {
list: [],
status: 'idle',
error: null,
},
reducers: {
addProduct: {
reducer: (state, action) => {
state.list.push(action.payload);
},
prepare(value) {
return {
payload: {
key: value.id,
value: value,
},
};
},
},
},
extraReducers: {
[getProducts.pending]: (state, action) => {
state.status = 'loading';
},
[getProducts.fulfilled]: (state, action) => {
state.status = 'succeeded';
state.list.push(...action.payload);
},
[getProducts.rejected]: (state, action) => {
state.status = 'failed';
state.error = action.error.message;
},
},
});
export const { addProduct } = listOfProducts.actions;
export default listOfProducts.reducer;
component with console.log
import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';
import { useSelector } from "react-redux";
const ShopCards = () => {
console.log(useSelector(state=>state))
return (
<div>
</div>
);
};
export default ShopCards;
The issue is that you are not dispatching the getProducts at all, you should dispatch this action and get the state with useSelector(state => state.shop) to select the proper reducer state. Try to change your code to the following:
import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';
// Don't forget to change the path
import { getProducts } from './path/to/reducer'
import { useSelector, useDispatch } from "react-redux";
import { useEffect } from "react";
const ShopCards = () => {
const products = useSelector((state) => {state.shop});
useEffect(() => {
// dispatch the action on first render
useDispatch(getProducts());
}, []);
useEffect(() => {
// print the products if the fetch to backend was made successfully
console.log(products);
}, [products]);
return (
<div>
</div>
);
};
export default ShopCards;
Other thing, in your createAsyncThunk you are returning response.data, so to fulfill properly the state, your api response should looks like this:
{
// you must return a JSON with data key who has an array of your products
// the content of product was just an example, so ignore it
data: [{id: 1, product: "foo"}]
}

I keep getting [Unhandled promise rejection: Error: Request failed with status code 404] while deleting a post from my API in React Native

I just started coding and I tried to delete a post through my mongoDB API. The code that I used is pretty basic, my API requests all go through a reducer which is set up pretty clear. But when I try to delete a post from my DB, I get the error ''[Unhandled promise rejection: Error: Request failed with status code 404]''. Did I do something wrong here or is this a mongoDB problem? I've included the necessary code.
This is my reducer request:
const deleteWorkout = (dispatch) => {
return async (_id) => {
await trackerApi.delete(`/workouts/${_id}`);
dispatch({ type: "delete_workout", payload: _id });
};
};
This is my complete reducer code:
import createWorkoutDataContext from "./createWorkoutDataContext";
import trackerApi from "../api/tracker";
const workoutReducer = (workouts, action) => {
switch (action.type) {
case "get_workouts":
return action.payload;
case "add_workout":
return [
...workouts,
{
title: action.payload.title,
exercises: action.payload.exercises,
},
];
case "edit_workout":
return workouts.map((Workout) => {
return Workout._id === action.payload.id ? action.payload : Workout;
});
case "delete_workout":
return workouts.filter((Workout) => Workout._id !== action.payload);
default:
return workouts;
}
};
const getWorkouts = (dispatch) => async () => {
const response = await trackerApi.get("/workouts");
dispatch({ type: "get_workouts", payload: response.data });
};
const addWorkout = (dispatch) => {
return async (title, exercises, callback) => {
await trackerApi.post("/workouts", { title, exercises });
if (callback) {
callback();
}
};
};
const editWorkout = (dispatch) => {
return async (title, exercises, _id, callback) => {
await trackerApi.put(`/workouts/${_id}`, { title, exercises });
dispatch({ type: "edit_workout", payload: { _id, title, exercises } });
if (callback) {
callback();
}
};
};
const deleteWorkout = (dispatch) => {
return async (_id) => {
await trackerApi.delete(`/workouts/${_id}`);
dispatch({ type: "delete_workout", payload: _id });
};
};
export const { Context, Provider } = createWorkoutDataContext(
workoutReducer,
{ addWorkout, getWorkouts, deleteWorkout },
[]
);
This is my code where I use the delete function:
const WorkoutListScreen = () => {
const { workouts, getWorkouts, deleteWorkout } = useContext(WorkoutContext);
return (
<View style={styles.container}>
<Text style={styles.pageTitle}>My Workouts</Text>
<NavigationEvents onWillFocus={getWorkouts} />
<FlatList
data={workouts}
keyExtractor={(item) => item._id}
renderItem={({ item }) => {
return (
<TouchableOpacity
onPress={() => navigate("WorkoutDetail", { _id: item._id })}
>
<View style={styles.row}>
<Text style={styles.title}>{item.title}</Text>
<TouchableOpacity onPress={() => deleteWorkout(item._id)}>
<Ionicons style={styles.deleteIcon} name="trash-outline" />
</TouchableOpacity>
</View>
</TouchableOpacity>
);
}}
/>
I simply included the deleteWorkout function in my TouchableOpacity, so I suppose that the problem lies within the reducer code?
here is the error I keep getting:
[Unhandled promise rejection: Error: Request failed with status code 404]
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\core\settle.js:17:22 in settle
at node_modules\axios\lib\adapters\xhr.js:66:12 in onloadend
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:614:6 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:10 in EventEmitter#emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue
This is what the objects in my databse look like (through Postman):
{
"userId": "615e06f36ce5e5f1a69c675e",
"title": "Defaults test",
"exercises": [
{
"exerciseTitle": "shadowboxing",
"exerciseProps": {
"time": 0,
"sets": 0,
"reps": 0
},
"_id": "6184c6fa685291fb44778df7"
},
{
"exerciseTitle": "bag workout",
"exerciseProps": {
"time": 4,
"sets": 0,
"reps": 12
},
"_id": "6184c6fa685291fb44778df8"
},
{
"exerciseTitle": "Exercise",
"exerciseProps": {
"time": 4,
"sets": 3,
"reps": 12
},
"_id": "6184c6fa685291fb44778df9"
}
],
"_id": "6184c6fa685291fb44778df6",
"__v": 0
}
I'm gratefull for your help!

delete item from apiCall need reload page to deleted from client

i use redux toolkit with react native and mongodb (mongoose)
i delete item and it successfully deleted from db
but not in client and need to reload page
todoSlice :
import {createSlice} from '#reduxjs/toolkit';
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state
},
},
});
export const {deleteTodo} = todoSlice.actions;
export default todoSlice.reducer;
apiCall:
import axios from 'axios';
import {deleteTodo} from './todoSlice';
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo());
} catch (err) {
console.log(err);
}
};
main :
const {todo} = useSelector(state => state);
const dispatch = useDispatch();
const {todos} = todo;
useEffect(() => {
getTodos(dispatch);
}, []);
const handleDelete = id => {
deleteOneTodo(id, dispatch);
};
you have to implement deleteTodo inside your todoSlice in order to remove the deleted id from your local state,
...
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state.filter((todo)=>todo.id!==action.payload.id);
},
},
});
...
and of course you have to pass the payload with the id of the todo you want to remove
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo({id:id}));
} catch (err) {
console.log(err);
}
};
if you still have doubts you can follow this tutorial: https://www.youtube.com/watch?v=fiesH6WU63I
i just call 'getTodos' inside 'deleteOneTodo'
and delete 'deleteTodo' from reducer
i hope its a good practice
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
// i add this line =>
getTodos(dispatch);
} catch (err) {
console.log(err);
}
};