I have a question and at the same time ask you for help because I have a problem in my coding.
So, I intend to display the "City" menu based on the "Province" parameter in my menu component tree.
I previously managed to display the provincial name menu in the tree menu component, the result is like this.
Well, later when the menu names of the provinces will appear the names of the cities based on the "province" parameter. However, when I tried it, it failed. The result is like this
Here's my code =
Building.js
export const getBuildingOLDallProvinsi = () => {
return new Promise((resolve, reject) => {
axios
.get(`${baseUrl}/api/nad/buildingCount`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
resolve(response.data.data);
})
.catch((error) => {
if (error.response?.data.code === 404)
resolve({ lists: [], totalCount: 0 });
console.log(error.response);
reject(error?.response?.data?.message || "Network error.");
});
});
};
export const getBuildingOLDallKota = (provinsi) => {
return new Promise((resolve, reject) => {
axios
.get(`${baseUrl}/api/nad/buildingCount/${provinsi}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
resolve(response.data.data);
})
.catch((error) => {
if (error.response?.data.code === 404)
resolve({ lists: [], totalCount: 0 });
console.log(error.response);
reject(error?.response?.data?.message || "Network error.");
});
});
};
TreeData.jsx
import React, { useEffect, useState } from "react";
import TreeMenu from "react-simple-tree-menu";
import "react-simple-tree-menu/dist/main.css";
import {
getBuildingOLDallProvinsi,
getBuildingOLDallKota,
} from "../../../service/building";
import { useParams } from "react-router-dom";
const TreeData = () => {
const [countData, setCount] = useState([]);
const [countData2, setCount2] = useState([]);
const getDataAllProvinsi = () => {
getBuildingOLDallProvinsi()
.then((resolve) => {
console.log(resolve);
setCount(resolve);
})
.catch((reject) => {
console.log(reject);
});
};
const { provinsi } = useParams();
const getDataAllKota = (param) => {
getBuildingOLDallKota({ ...param, provinsi: provinsi })
.then((resolve) => {
console.log(resolve);
setCount2(resolve);
})
.catch((reject) => {
console.log(reject);
});
};
useEffect(() => {
getDataAllProvinsi();
getDataAllKota();
}, []);
return (
<>
<div className="row">
<div className="col text-center">
<p className="mt-3">
<div className="row mt-3 d-flex justify-content-center cursor-pointer">
<div className="col-lg-8 text-left text-dark">
<TreeMenu
cacheSearch
data={[
{
key: "provinsi",
label: "Provinsi",
nodes: countData.map((data) => {
return {
key: data.id,
label: [data.provinsi, data.total_building],
nodes: [
{
key: "kota",
label: "Kota",
nodes: countData2.map((data) => {
return {
key: data.provinsi,
label: [data.kota, data.total_building],
nodes: [
{
key: data.id,
label: data.total_building,
nodes: [],
},
],
};
}),
},
],
};
}),
},
]}
debounceTime={125}
disableKeyboard={false}
hasSearch={false}
onClickItem={function noRefCheck() {}}
resetOpenNodesOnDataUpdate={false}
/>
</div>
</div>
</p>
</div>
</div>
</>
);
};
export default TreeData;
Thank you in advance, your help is very helpful for me and I really respect all of your answers.
Edit = this is my response API
pastebin(dot)com/Bua3FThZ
pastebin(dot)com/ERSCHDSR
Update:
In the console I can display param data based on the province.
For example, the data for the province is "ACEH", then the ACEH data appears in the console ...
const getDataAllKota = (param) => {
getBuildingOLDallKota("ACEH")
.then((resolve) => {
console.log(resolve);
setCount2(resolve);
})
.catch((reject) => {
console.log(reject);
});
};
console.log(countData2);
Now I'm confused about how to display param data by province in the component tree menu.
Related
I have two components.
DropDownForRoomChangeCondo.js js that displays radio buttons. DiscoverCondoRoom.js displays DropDownForRoomChangeCondo.js.
What I want to achieve is In DropDownForRoomChangeCondo.js, When sending a request to the backend with handleChange (when switching the radio button) I want to change the screen display by calling getDevices(); in DiscoverCondoRoom.js. (Since the assignment of the room where the device is installed changes when the radio button is switched, I want to update the display)
Issue/error message
Currently, when sending a request to the backend with handleChange (when switching the radio button) Display update does not occur.
DropDownForRoomChangeCondo.js
import Dropdown from 'react-bootstrap/Dropdown';
const DropDownForRoomChangeCondo = (item) => {
const history = useHistory();
const [devices, setDevices] = useState([]);
const handleChange = e => {
setVal(e.target.name);
setDeviceRoomName(e.target.name);
}
const setDeviceRoomName = async(data) => {
console.log("Body sent to server", {
attributes:
[
{
entity_id : item.item.entity_id,
room_name: data
}
]
})
await axios.post('xxx.com',
{
attributes:
[
{
entity_id : item.item.entity_id,
room_name: data
}
]
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log('Set Device Room Name!');
getDevices();
})
.catch(err => {
console.log(err);
console.log('Missed Set Device Room Name!');
});
}
const getDevices = async(data) => {
await axios.get('xxx.com',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
console.log("bbbbbbbbbbb")
setDevices(result.data.attributes);
})
.catch(err => {
console.log(err);
});
}
const keys = [
"camera",
"climate",
"cover",
"light",
"lock",
"sensor",
"switch",
];
const entities = keys
.map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
.flat();
const roomNames = [...new Set(entities.map((entity) => entity.room_name))];
const [val, setVal] = useState(item.item.room_name);
console.log(val)
console.log(typeof(val))
const CustomToggle = React.forwardRef(({ children, onClick }, ref) => (
<a
href=""
ref={ref}
onClick={(e) => {
e.preventDefault();
onClick(e);
}}
>
{children}
<img className="ic_edit" src={ic_edit} />
</a>
));
useEffect(() => {
getDevices();
},[]);
return (
<>
<div className="">
<p>{item.item.room_name}</p>
<Dropdown className="room_change_dropdown_top">
<Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components" />
<Dropdown.Menu className="room_change_dropdown">
<Dropdown.Item className="room_change_dropdown_item">
{roomNames.map((room_names, i) => (
<div className="flex_radio">
<input
className="room_change_radio"
type="radio"
value={room_names}
name={room_names}
onChange={handleChange}
checked={val === room_names}
/>
<p className="drop_down_p">{room_names}</p>
</div>
))}
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</div>
</>
);
}
export default DropDownForRoomChangeCondo;
DiscoverCondoRoom.js
const DiscoverCondoRoom = () => {
const history = useHistory();
const [devices, setDevices] = useState([]);
const getDevices = async(data) => {
await axios.get('xxx.com',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
setDevices(result.data.attributes);
})
.catch(err => {
console.log(err);
});
}
useEffect(() => {
getDevices();
},[]);
const lll = Object.keys(devices);
const object_device_value = Object.values(devices).flat();
const keys = [
"camera",
"climate",
"cover",
"light",
"lock",
"sensor",
"switch",
];
const entities = keys
.map((key) => (devices[key] || []).map((e) => ({ ...e, key })))
.flat();
const roomNames = [...new Set(entities.map((entity) => entity.room_name))];
return (
<>
<div className="container condo_container">
{entities.map((entity, i) => (
<DropDownForRoomChangeCondo item={entity} />
))}
</div>
</>
);
}
};
export default DiscoverCondoRoom;
You need to pass your getDevices Method as a prop to your dropdown component.
<DropDownForRoomChangeCondo item={entity} getDevices={getDevices} />
Then inside your DropDown Component, call the getDevices Method at your desired place by calling props.getDevices().
Also, i would suggest to define props like so:
const DropDownForRoomChangeCondo = (props) => {
const history = useHistory();
const [devices, setDevices] = useState([]);
…
And then access item by pointing to props.item
I have 2 Api requests, one of them hangs on the child - from it, when I click on the picture, I get the track key and give it to the parent in the second Api request as a parameter so that it displays the information I need. But when I output this to the console, I get an empty message =(
result console.log
CHILD
import React from 'react'
import { AppContext } from '../MainContent'
import TrackTranding from './TrackTranding'
const ContentTrending = ({ onClick }) => {
const { articles, setArticles } = React.useContext(AppContext)
const handleClick = (e) => {
e.preventDefault();
onClick(articles[e.target.dataset.attr].key) // get key from first api
}
return (
<div className="main__content-trending">
<p>Tranding right now</p>
<div className="noflex-oneblock">
<div className="main__content-trending-artist-title ">
{
articles.map((tracks, index) => {
return (
<div className='one' key={tracks.key}
onClick={handleClick}
>
<TrackTranding
tracks={tracks}
index={index}
/>
<audio src="#" id="audioTrack"></audio>
</div>
)
})
}
</div>
</div>
</div>
)
}
export default ContentTrending
PARENT
import axios from 'axios'
import React from 'react'
import MainContentBg from './MainBcg/ContentBg'
import MainContentTitle from './MainTitle/ContentTitle'
import ContentTrending from './MainTrending/ContentTrending'
export const AppContext = React.createContext()
const MainContent = () => {
const [articles, setArticles] = React.useState([])
const [detailse, setDetailse] = React.useState([])
const [name, setName] = React.useState('');
const handleClick = (name) => {
setName(name)
console.log(detailse) // --------------------------- error =()
}
const fetchData = () => {
const chart = {
method: 'GET',
url: 'https://shazam.p.rapidapi.com/charts/track',
params: { locale: 'en-US', pageSize: '20', startFrom: '0' },
headers: {
'X-RapidAPI-Key': '10eb9d1c65msh1029069c658be40p1197a5jsne7f1ee8c9f88',
'X-RapidAPI-Host': 'shazam.p.rapidapi.com'
}
};
axios.request(chart).then(data => {
const tracksApi = data.data.tracks
setArticles(tracksApi)
})
const details = {
method: 'GET',
url: 'https://shazam.p.rapidapi.com/songs/get-details',
params: { key: { name }, locale: 'en-US' }, // ---------------------------------- param
headers: {
'X-RapidAPI-Key': '10eb9d1c65msh1029069c658be40p1197a5jsne7f1ee8c9f88',
'X-RapidAPI-Host': 'shazam.p.rapidapi.com'
}
};
axios.request(details).then(data => {
const tracksDetails = data.data
setDetailse(tracksDetails)
})
}
React.useEffect(() => {
fetchData()
}, []);
return (
<main className="main">
<div className="main__content">
<AppContext.Provider value={{ articles, setArticles }}>
<MainContentTitle />
<MainContentBg />
<ContentTrending onClick={handleClick} />
</AppContext.Provider>
</div>
</main>
)
}
export default MainContent
Currently you call fetchData when the component first mounts the name state is set to an empty string "".
React.useEffect(() => {
fetchData();
}, []);
Which you're passing in the details so essentially the object looks like this:
const details = {
method: "GET",
url: "https://shazam.p.rapidapi.com/songs/get-details",
params: { key: { name: "" }, locale: "en-US" }, // notice the empty string
headers: {
"X-RapidAPI-Key": "10eb9d1c65msh1029069c658be40p1197a5jsne7f1ee8c9f88",
"X-RapidAPI-Host": "shazam.p.rapidapi.com",
},
};
Instead what you can do is trigger the useEffect when the name changes. Which will now have the updated name from the handleClick from the Child.
React.useEffect(() => {
fetchData();
}, [name]);
You probably want to change, currently you're setting the key to a object with another prop called name.
params: { key: { name }, locale: 'en-US' }
to, this will make sure the key prop has the value from name
params: { key: name, locale: 'en-US' }
i've a component that i import, but its not displayed on the page.
this is my app.js file. i imported the <LineGraph/>component but it is not getting displayed properly on the browser.
import React, { useEffect, useState } from "react";
import {
MenuItem,
FormControl,
Select,
Card,
CardContent,
} from "#material-ui/core";
import InfoBox from "./infoBox";
import Table from "./table";
import "./App.css";
import { sortData } from "./util";
import LineGraph from "./LineGraph";
const App = () =\> {
const \[countries, setCountries\] = useState(\[\]);
const \[country, setCountry\] = useState("worldwide");
const \[countryInfo, setCountryInfo\] = useState({});
const \[tableData, setTableData\] = useState(\[\]);
const \[casesType, setCasesType\] = useState("cases");
useEffect(() =\> {
fetch("https://disease.sh/v3/covid-19/all")
.then((response) =\> response.json())
.then((data) =\> {
setCountryInfo(data);
});
}, \[\]);
useEffect(() =\> {
const getCountriesData = async () =\> {
fetch("https://disease.sh/v3/covid-19/countries")
.then((response) =\> response.json())
.then((data) =\> {
const countries = data.map((country) =\> ({
name: country.country,
value: country.countryInfo.iso2,
}));
const sortedData = sortData(data);
setTableData(sortedData);
setCountries(countries);
});
};
getCountriesData();
}, \[\]);
const onCountryChange = async (event) =\> {
const countryCode = event.target.value;
console.log("s", countryCode);
setCountry(countryCode);
const url =
countryCode === "worldwide"
? "https://disease.sh/v3/covid-19/all"
: `https://disease.sh/v3/covid-19/countries/${countryCode}`;
await fetch(url)
.then((response) => response.json())
.then((data) => {
setCountry(countryCode);
setCountryInfo(data);
});
};
console.log("CuntryInfo: ", countryInfo);
return (
\<div className="App"\>
\<div className="app__left"\>
\<div className="app__header"\>
\<h1\>COVID-19 Tracker\</h1\>
\<FormControl className="app__dropdown"\>
\<Select
variant="outlined"
onChange={onCountryChange}
value={country}
\\>
\<MenuItem value="worldwide"\>Worldwide\</MenuItem\>
{countries.map((country) =\> (
\<MenuItem value={country.value}\>{country.name}\</MenuItem\>
))}
\</Select\>
\</FormControl\>
\</div\>
<div className="app__stats">
<InfoBox
title="Coronavirus cases"
cases={countryInfo.todayCases}
total={countryInfo.cases}
/>
<InfoBox
title="Recovered"
cases={countryInfo.todayRecovered}
total={countryInfo.recovered}
/>
<InfoBox
title="Deaths"
cases={countryInfo.todayDeaths}
total={countryInfo.deaths}
/>
</div>
</div>
<Card className="app__right">
<CardContent>
{/* Table */}
<h3>Live Cases by country</h3>
<Table countries={tableData} />
{/* Graph */}
<h3>Word Wide New </h3>
<LineGraph casesType={casesType} />
</CardContent>
</Card>
</div>
);
};
export default App;
and My content of LineGraph.js :
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import numeral from "numeral";
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 0,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,0");
},
},
},
};
const buildChartData = (data, casesType) => {
let chartData = [];
let lastDataPoint;
for (let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint,
};
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
.then((response) => {
return response.json();
})
.then((data) => {
let chartData = buildChartData(data, casesType);
setData(chartData);
console.log(chartData);
// buildChart(chartData);
});
};
fetchData();
}, [casesType]);
return (
<div>
{data?.length > 0 && (
<Line
data={{
datasets: [
{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data,
},
],
}}
options={options}
/>
)}
</div>
);
}
export default LineGraph;
When I import the LineGraph.js component in the App.js file, the output is not displayed without any error.
in console error is :
react-dom.development.js:25830
Uncaught Error: "category" is not a registered scale.
I'm trying to adjust my countInStock based off of qty ordered. In my PlaceOrderScreen.js, I have items = item.map(product => ({ _id: product._id, countInStock: product.countInStock, qty: product.qty, new:(product.countInStock - product.qty) })) where item = cart.carItems. I'm trying to get this to my backend in my productRouter.js, so that I can update my products based off of their new countInStock, but I'm getting "Cast to ObjectId failed for value \"updateInstock\" (type string) at path \"_id\" for model \"Product\". I'm unsure of why this is happening, and I would really appreciate any help or advice. Thank you!
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {createOrder} from '../actions/orderActions';
import {updateInstock} from '../actions/productActions';
import { ORDER_CREATE_RESET } from '../constants/orderConstants';
export default function PlaceOrderScreen(props) {
const cart = useSelector((state) => state.cart);
if (!cart.paymentMethod) {
props.history.push('/payment');
}
const orderCreate = useSelector((state) => state.orderCreate);
const { loading, success, error, order } = orderCreate;
const item = cart.cartItems
const items = item.map(product => ({ _id: product._id, countInStock: product.countInStock, qty: product.qty, new:(product.countInStock - product.qty) }))
const dispatch = useDispatch();
const placeOrderHandler = () => {
dispatch(createOrder({ ...cart, orderItems: cart.cartItems }));
dispatch(updateInstock(items));
};
useEffect(() => {
if (success) {
props.history.push(`/order/${order._id}`);
dispatch({ type: ORDER_CREATE_RESET });
}
}, [dispatch, order, props.history, success]);
return (
<div>
<div className="row top">
<div className="col-1">
<div className="card card-body">
<ul>
<li>
<div className="row">
...
</div>
</li>
<li>
<button
type="button"
onClick={placeOrderHandler}
className="primary block"
disabled={cart.cartItems.length === 0}
>
Place Order
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
);
}
productActions.js
import Axios from 'axios';
import {
PRODUCT_UPDATEINSTOCK_REQUEST,
PRODUCT_UPDATEINSTOCK_SUCCESS,
PRODUCT_UPDATEINSTOCK_FAIL,
} from '../constants/productConstants';
import { BASE_URL } from '../constants/app.constants';
export const updateInstock = (items) => async (dispatch, getState) => {
dispatch({ type: PRODUCT_UPDATEINSTOCK_REQUEST, payload: items });
const {
userSignin: { userInfo },
} = getState();
try {
const { data } = await Axios.put(`${BASE_URL}/api/products/updateInstock`, items, {
headers: { Authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: PRODUCT_UPDATEINSTOCK_SUCCESS, payload: data });
} catch (error) {
const message = error.response && error.response.data.message ? error.response.data.message : error.message;
dispatch({ type: PRODUCT_UPDATEINSTOCK_FAIL, error: message });
}
};
productRouter.js
productRouter.put(
'/updateInstock',
expressAsyncHandler(async (req, res) => {
console.log(req.body.items)
})
);
console.log(req.body.items) is not showing data in the terminal.
I tired to put checked and unchecked on the input checkbox.
Indeed i have a list of checkbox items, i get them form API, Then i would like to crossed or leave unchecked them and send to data base. I crossed some of them and i can successfully get the crossed checkboxes from database. Now i try to uncheck them and i post them again. In the next time, when i reload the page i see there are still crossed checkboxes.
here you can see the code.
Can any one to solve my puzzle?
Her you can see the part of my code.
Thank you.
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState("");
const [selectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
let intIds = response?.data?.interests; // intIds it is Array like intIds =[{"id": 1, "name": "drink"}, ...] or empty
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = [];
for (let inter of response.data) { //here: response.data=[{"id": 1, "name": "drink"}, ...]
interestItems.push(
<div className="col-6" key={inter.id}>
<div className="row">
<div className="col-2">
<input
key={inter.id}
id={inter.id}
name="newsletter"
type="checkbox"
onChange={(e) =>{ console.log(e, e.target)
return interestChange(e.target)}}
/>
</div>
<div className="col-10">
<p className="p-14">{inter.name}</p>
</div>
</div>
</div>
);
}
setInterests(interestItems);
for (let elem of intIds) {
document.getElementById(elem.id).setAttribute("checked", "checked");
selectedInterests.push(elem.id);
}
})
.catch((err) => {
console.log(err);
});
});
}, []);
const interestChange = (elem) => {
console.log(elem, elem.checked, elem.id);
console.log(selectedInterests);
if (elem.checked) {
selectedInterests.push(parseInt(elem.id));
console.log(selectedInterests);
}
else {
let newInterests = selectedInterests;
newInterests.splice(newInterests.indexOf(parseInt(elem.id)), 1);
console.log(newInterests);
}
}
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">
{interests}
</div>
</Form>
</div>
</div>
);
}
export default UserProfile;
Here i try to found the solution for my puzzle
import React, { useContext, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Csc from "country-state-city";
import { useHistory, useLocation } from "react-router-dom";
import salone from "../utils/salone";
function UserProfile(props) {
const [interests, setInterests] = React.useState({});
const [selectedInterests, setSelectedInterests] = React.useState([]);
useEffect(() => {
salone.get(`/user/info`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
})
.catch((error) => {
console.log(error.response.data.detail);
history.push("/login");
})
.then((response) => {
if(Array.isArray(response?.data?.interests)){
setSelectedInterests(response?.data?.interests.map((interest) => interest.id));
}
salone.get(`/auth/signup/interests`)
.then((response) => {
let interestItems = {};
for (let inter of response.data) {
interestItems[inter.id]= inter;
}
setInterests(interestItems);
})
.catch((err) => {
console.log(err);
});
});
}, []);
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
let url = `/user/update?interest_id_list=${selectedInterests.join(",")}`;
salone.post(url,
null,
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
)
.then((response) => {
if (response != undefined) {
history.push({
pathname: "/message",
state: {
message: "Aggiornamento effettuato con successo!",
type: "confirm",
back: true,
//link: "/login",
//label: "Go back to Login page",
img: imgNotification}
});
}
})
.catch((err) => {
}
});
}
};
return (
<div>
<div className="row w-100 m-0">
<Form method="post" onSubmit={handleSubmit}>
<div className="row mt-2">{Object.keys(interests).map((interstId) => {
interstId = +interstId;
let interest = interests[interstId];
//console.log(selectedInterests, interstId,
selectedInterests.indexOf(interstId));
return <div className="col-6" key={interest.id}>
<div className="row">
<div className="col-2">
<input
key={interest.id}
id={interest.id}
name="newsletter"
type="checkbox"
checked = {selectedInterests.indexOf(interstId) > -1 ? "checked" : ""}
onChange={(e) =>{
let index = selectedInterests.indexOf(interstId);
if(index > -1){
selectedInterests.splice(index, 1);
setSelectedInterests([...selectedInterests])
}else{
setSelectedInterests([...selectedInterests, interstId])
}
}}
/>
</div>
<div className="col-10">
<p className="p-14">{interest.name}</p>
</div>
</div>
</div>
})}</div>
</Form>
</div>
</div>
);
}
export default UserProfile;