I am able to post and get data but unable to delete must be a problem with an id that I am passing to the delete note function.
these are my files:
Note.js
import React, {useState} from 'react';
import DeleteIcon from '#material-ui/icons/Delete';
import EditIcon from '#material-ui/icons/Edit';
import SaveIcon from '#material-ui/icons/Save';
function Note(props) {
function handleClick() {
props.onDelete(props.id);
}
const[edit, setEdit]=useState(false);
function editTrue() {
setEdit(!edit);
}
return(
<div className={!edit ? "note" : "note1"}>
<h1 contentEditable={edit && "true"} spellCheck="true">{props.title}</h1>
<hr/>
<p />
<p contentEditable={edit && "true"} spellCheck="true">{props.content}</p>
{!edit && <button onClick={handleClick}><DeleteIcon /></button>}
{edit ? <button onClick={editTrue}> <SaveIcon /> </button> : <button onClick={editTrue}><EditIcon /></button>}
</div>
);
}
export default Note;
App.js
import React, { useState, useEffect } from 'react';
//import { DragDropContext } from 'react-beautiful-dnd';
import Header from './Header';
import Footer from './Footer';
import Note from './Note';
import CreateArea from './CreateArea'
function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
fetch('https://react-hooks-update-ec587-default-rtdb.firebaseio.com/notes.json')
.then(response => response.json())
.then(responseData => {
const loadedNotes = [];
for( const key in responseData ) {
loadedNotes.push({
id: key,
title: responseData[key].title,
content: responseData[key].content
});
}
setNotes(loadedNotes);
});
}, []);
function addNote(newNote) {
fetch('https://react-hooks-update-ec587-default-rtdb.firebaseio.com/notes.json', {
method: 'POST',
body: JSON.stringify(newNote),
headers: { 'content-Type': 'application/json' }
}).then(response => {
return response.json();
}).then(responseData => {
setNotes(prevNotes => [
...prevNotes,
{ id: responseData.name, ...newNote }
]);
});
}
function deleteNote(noteId) {
fetch(`https://react-hooks-update-ec587-default-rtdb.firebaseio.com/notes/${noteId}.json`,
{
method: 'DELETE'
}
).then(response => {
setNotes(prevNotes => {
return prevNotes.filter((noteItem, index) => {
return index !== noteId;
});
});
});
}
return(
<div>
<Header />
<CreateArea
onAdd={addNote}
/>
{notes.map((noteItem, index) => {
return (
<Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/>
);
})}
<Footer />
</div>
);
}
export default App;
what changes I can do?
when I run my file delete operation is working locally but it does not delete the note from the database
I am able to post and get data but unable to delete must be a problem with an id that I am passing to the delete note function.
May be in deleteNote in fetch url remove .json:
fetch(`https://react-hooks-update-ec587-default-rtdb.firebaseio.com/notes/${noteId}`)
Related
after onclick event occurs in backpackList.js, fetch data in context.js and then through setState I want to update noneUserCart . After that i want to get data from context.js to backpackList.js to show web page. but the data is inital data []. How can I solve this problem?!
I think this is a Asynchronous problem, but I'm new react, so I don't know how to write code for this. or do I use async, await.
Help me please!
import React, { Component } from 'react';
const ProductContext = React.createContext();
const ProductConsumer = ProductContext.Consumer;
class ProductProvider extends Component {
constructor() {
super();
this.state = {
totalProducts: 0,
isLogin: false,
cartList: [],
isNavOpen: false,
isCartOpen: false,
noneUserCart: [],
};
}
noneUserAddCart = bagId => {
fetch('/data/getdata.json', {
method: 'GET',
})
.then(res => res.json())
.catch(err => console.log(err))
.then(data => {
this.setState(
{
noneUserCart: [...this.state.noneUserCart, data],
},
() => console.log(this.state.noneUserCart)
);
});
};
render() {
return (
<ProductContext.Provider
value={{
...this.state,
handleCart: this.handleCart,
getToken: this.getToken,
addNoneUserCart: this.addNoneUserCart,
hanldeCheckout: this.hanldeCheckout,
openNav: this.openNav,
showCart: this.showCart,
habdleCartLsit: this.habdleCartLsit,
deleteCart: this.deleteCart,
noneUserAddCart: this.noneUserAddCart,
}}
>
{this.props.children}
</ProductContext.Provider>
);
}
}
export { ProductProvider, ProductConsumer };
import React, { Component } from 'react';
import { ProductConsumer } from '../../context';
export default class BackpackList extends Component {
render() {
const {
backpackdata,
backdescdata,
isdescOpen,
showDesc,
descClose,
rangenumone,
rangenumtwo,
} = this.props;
return (
<div>
{backdescdata.map((bag, inx) => {
return (
<>
{isdescOpen && bag.id > rangenumone && bag.id < rangenumtwo && (
<div className="listDescContainer" key={inx}>
<div className="listDescBox">
<ProductConsumer>
{value => (
<div
className="cartBtn"
onClick={() => {
const token = value.getToken();
if (token) {
value.handleCart(bag.id, token);
} else {
value.noneUserAddCart(bag.id);
console.log(value.noneUserCart);
// this part. value.noneUserCart is undefined
}
}}
>
add to cart.
</div>
)}
</ProductConsumer>
<span className="descClosebtn" onClick={descClose}>
X
</span>
</div>
</div>
</div>
)}
</>
);
})}
</div>
);
}
}
fetch is asynchronous, this.setState is yet called when console.log
<div
className="cartBtn"
onClick={() => {
const token = value.getToken();
if (token) {
value.handleCart(bag.id, token);
} else {
value.noneUserAddCart(bag.id);
console.log(value.noneUserCart);
// this part. value.noneUserCart is undefined
}
}}
>
add to cart.
{value.noneUserCart}
{/* when finished, result should show here */}
</div>
I have been doing js for about a month now, and I am writing this program where I am using clarifai API to see which celebrity a person on the photo resembles the most.
I want to pass the output as props to Rank component to render it, but
I get the
Type error: clarifaiResults.map is not a function at App.transformResponse
Basically, the response I want to pass as props is the
const clarifaiResults = response.outputs[0].data.regions[0].data.concepts[0].name;
part that I get in console.log now
I am assuming it's because there is no output yet when the app tries to render the component, but I can't figure out what's wrong with the code. Thank you!
App.js
import React, { Component } from 'react';
import './App.css';
import SignIn from './Component/SignIn/SignIn.js';
import Register from './Component/Register/Register.js';
import Particles from 'react-particles-js';
import Logo from './Component/Logo/Logo.js';
import Navigation from './Component/Navi/Navigation.js';
import ImageLinkForm from './Component/Form/ImageLinkForm.js';
import Rank from './Component/Rank/Rank.js'
import Clarifai from 'clarifai';
import FaceRecognition from './Component/Face/FaceRecognition.js';
import FaceComparison from './Component/Comparison/FaceComparison.js';
const app = new Clarifai.App({
apiKey: 'MYSUPERSECRETKEY'
});
const initialState = {
input: "",
imageUrl: "",
results: [],
route: "SignIn",
user: {
id: "",
name: "",
email: "",
entries: 0,
joined: "",
},
};
const particleOptions = {
particles: {
number: {
value: 40,
density: {
enable: true,
value_area: 800,
},
}
}
}
class App extends Component{
constructor() {
super();
this.state = initialState;
}
transformResponse = (response) => {
const clarifaiResults = response.outputs[0].data.regions[0].data.concepts[0].name;
const results = clarifaiResults.map((ingredient) => ({
ingredients: ingredient.name,
probablitiy: ingredient.value,
}));
this.setState({results: results.celebrityName});
return {results: []};
};
onInputChange = (event) => {
this.setState({input: event.target.value});
}
onSubmit = () => {
this.setState({imageUrl: this.state.input});
app.models
.predict(
Clarifai.CELEBRITY_MODEL,
this.state.input)
.then(response => {
console.log(response.outputs[0].data.regions[0].data.concepts[0].name)
if (response) {
fetch ('http://loclhost:3000', {
method: 'post',
headers: {'Conent-Type' : 'application/json'},
body: JSON.stringify({
input: this.state.user.input
})
})
.then((response) => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, {entries:count}))
})
}
this.transformResponse(response);
})
.catch(err => console.log(err));
};
;
onRouteChange = (route) => {
if (route === 'signout'){
this.setState({isSignedIn: false})
} else if (route ==='home'){
this.setState({isSignedIn: true})
}
this.setState({route: route});
}
render() {
let { isSignedIn, imageUrl, route, results} = this.state;
return (
<div className="App">
<Particles className='particles'
params={particleOptions}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange}/>
{ route ==='home'
? <div>
<Logo />
<Rank
results = {results}/>
<ImageLinkForm
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
/>
<FaceRecognition
imageUrl={imageUrl}
/>
<FaceComparison
results = {results}
/>
</div>
: (
route === 'SignIn'
? <SignIn onRouteChange={this.onRouteChange}/>
: <Register />
)
}
</div>
);
};
}
export default App;
Rank.js
import React from 'react';
const Rank = ({results}) => {
const prediction = results.map((result) => {
const {ingredients} = result;
return (
<div>
<li className="celebrityName">{ingredients}</li>
</div>
);
});
if (prediction && prediction.length>1) {
return (
<div>
<div className='white f3'>
You look a lot like...
</div>
<div className='white f1'>
{results}
</div>
</div>
);
} else {
return (
<div>
</div>
)
}
};
export default Rank;
I have the following code that passing leadsBuilder props to lead in the LeadBuilderSingle componenet. It has an array in a object and I access that array and try to map over it but it returns undefined. The data is being waited on and I am using isLoading, so I am not sure what is causing this error. It loads on first loading, but on page refresh gives me undefined.
import React, { useState, useEffect } from "react";
import Dasboard from "./Dashboard";
import { Container } from "../styles/Main";
import { LeadsBuilderCollection } from "../../api/LeadsCollection";
import { LeadBuilderSingle } from "../leads/LeadBuilderSingle";
import { useTracker } from "meteor/react-meteor-data";
const LeadCategoriesAdd = ({ params }) => {
const { leadsBuilder, isLoading } = useTracker(() => {
const noDataAvailable = { leadsBuilder: [] };
if (!Meteor.user()) {
return noDataAvailable;
}
const handler = Meteor.subscribe("leadsBuilder");
if (!handler.ready()) {
return { ...noDataAvailable, isLoading: true };
}
const leadsBuilder = LeadsBuilderCollection.findOne({ _id: params._id });
return { leadsBuilder };
});
return (
<Container>
<Dasboard />
<main className="">
{isLoading ? (
<div className="loading">loading...</div>
) : (
<>
<LeadBuilderSingle key={params._id} lead={leadsBuilder} />
</>
)}
</main>
</Container>
);
};
export default LeadCategoriesAdd;
import React from "react";
export const LeadBuilderSingle = ({ lead, onDeleteClick }) => {
console.log(lead);
return (
<>
<li>{lead.type}</li>
{lead.inputs.map((input, i) => {
return <p key={i}>{input.inputType}</p>;
})}
</>
);
};
FlowRouter.route("/leadCategories/:_id", {
name: "leadeBuilder",
action(params) {
mount(App, {
content: <LeadCategoriesAdd params={params} />,
});
},
});
try this :
lead.inputs && lead.inputs.map ((input, i) => {...}
After using a form and inserting new data this error show up.
This is my code:
import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";
import hashHistory from './hashHistory';
const FormItem = Form.Item;
class CustomForm extends React.Component {
handleFormSubmit = async (event, requestType, articleID) => {
event.preventDefault();
const postObj = {
title: event.target.elements.title.value,
content: event.target.elements.content.value
}
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.headers = {
"Content-Type": "application/json",
Authorization: `Token ${this.props.token}`,
};
if (requestType === "post") {
await axios.post("http://192.168.196.49:8000/api/create/", postObj)
.then(res => {
if (res.status === 201) {
//this.props.history.push(`/articles/`);
//this.props.hashHistory.push('/');
//hashHistory.push(String('/articles/'))
this.props.history.push({
pathname: "/"
})
}
})
} else if (requestType === "put") {
await axios.put(`http://192.168.196.49:8000/api/${articleID}/update/`, postObj)
.then(res => {
if (res.status === 200) {
//this.props.history.push(`/articles/`);
//this.props.hashHistory.push('/');
//hashHistory.push(String('/articles/'))
this.props.history.push({
pathname: "/"
})
}
})
}
};
render() {
console.log("debug:", this.props)
return (
<div>
<Form
onSubmit={event =>
this.handleFormSubmit(
event,
this.props.requestType,
this.props.articleID
)
}
>
<FormItem label="TÃtulo">
<Input name="title" placeholder="Put a title here" />
</FormItem>
<FormItem label="Comentario">
<Input name="content" placeholder="Enter some content ..." />
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
{this.props.btnText}
</Button>
</FormItem>
</Form>
</div>
);
}
}
const mapStateToProps = state => {
return {
token: state.token
};
};
export default connect(mapStateToProps)(CustomForm);
Routes
<Route exact path="/articles/" component={ArticleList} />{" "}
<Route exact path="/articles/:articleID/" component={ArticleDetail} />{" "}
Error message:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
The data is storing correcty to the database, but just after submiting there is this error.
My original code was using history.push but tried hashHistory.push.
I am using redux in the proyect.
Verision using:
react-router 5.1.2
history 4.9.0
Try make a module hashHistory:
// hashHistory.js
import { createHashHistory } from 'history'; // worked for the OP
export default createHashHistory({});
And use it:
const history = createHashHistory();
// ....
// **EDIT** This should work
history.push("/articles/")
You can use withRouter to push history in props.
import { withRouter } from 'react-router';
const SpecialButton = withRouter(({ history, path, text }) => {
return (
<Button
onClick={() => { history.push(path); }}
>
{text}
</Button>
)
});
This was the solution that works (may be is not the best one...)
code:
import React from "react";
import { Form, Input, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";
import { createHashHistory } from 'history'
const FormItem = Form.Item;
class CustomForm extends React.Component {
handleFormSubmit = async (event, requestType, articleID) => {
event.preventDefault();
const postObj = {
title: event.target.elements.title.value,
content: event.target.elements.content.value
}
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.headers = {
"Content-Type": "application/json",
Authorization: `Token ${this.props.token}`,
};
const history = createHashHistory();
if (requestType === "post") {
console.log("debug_1.1_Form_post_history: ", history )
await axios.post("http://192.168.196.49:8000/api/create/", postObj)
.then(res => {
if (res.status === 201) {
history.push("/articles/")
}
})
} else if (requestType === "put") {
console.log("debug_1.2_Form_put_history: ", history )
await axios.put(`http://192.168.196.49:8000/api/${articleID}/update/`, postObj)
.then(res => {
if (res.status === 200) {
console.log("debug_1.3_Form_put_this.props: ", this.props)
history.push("/articles/");
}
})
}
};
render() {
return (
<div>
<Form
onSubmit={event =>
this.handleFormSubmit(
event,
this.props.requestType,
this.props.articleID
)
}
>
<FormItem label="Title">
<Input name="title" placeholder="Put a title here" />
</FormItem>
<FormItem label="Content">
<Input name="content" placeholder="Enter some content ..." />
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
{this.props.btnText}
</Button>
</FormItem>
</Form>
</div>
);
}
}
const mapStateToProps = state => {
return {
token: state.token
};
};
export default connect(mapStateToProps)(CustomForm);
I need to send an array from React.js frontend to the Django backend. I can easily send all variables, except just an array csvData.
I see that console.log("csvData", csvData) returns the following data:
NUM,COL1,COL2
1,300,500
2,566,VL
This is the code of React component called BatchFlights:
import React, { Component, Fragment } from 'react';
import TopControls from "./layout/batch/TopControls"
import MainContent from "./layout/batch/MainContent"
import BottomControls from "./layout/batch/BottomControls"
import styles from "./layout/styles/styles";
import { withStyles } from "#material-ui/core/styles";
class BatchFlights extends Component {
constructor(props) {
super(props);
this.state = {
csvData: [],
temperature: 20,
visibility: 5999.66,
windIntensity: 8.0,
prediction: 0,
labelWidth: 0
};
this.handleChange = this.handleChange.bind(this);
};
componentDidMount() {
this.fetchData();
};
updateDelay(prediction) {
this.setState(prevState => ({
prediction: prediction
}));
};
setCsvData = csvData => {
this.setState({
csvData
}, () => {
console.log("csvData",this.state.csvData)
});
}
fetchData = () => {
const url = "http://localhost:8000/predict?"+
'&temperature='+this.state.temperature+
'&visibility='+this.state.visibility+
'&windIntensity='+this.state.windIntensity+
'&csvData='+this.state.csvData;
fetch(url, {
method: "GET",
dataType: "JSON",
headers: {
"Content-Type": "application/json; charset=utf-8",
}
})
.then((resp) => {
return resp.json()
})
.then((data) => {
this.updateDelay(data.prediction)
})
.catch((error) => {
console.log(error, "catch the hoop")
})
};
handleChange = (name, event) => {
this.setState({
[name]: event.target.value
}, () => {
console.log("csvData", csvData)
});
};
handleReset = () => {
this.setState({
prediction: 0
});
};
render() {
return (
<Fragment>
<TopControls state={this.state} styles={this.props.classes} handleChange={this.handleChange} />
<MainContent state={this.state} styles={this.props.classes} setCsvData={this.setCsvData} />
<BottomControls state={this.state} styles={this.props.classes} fetchData={this.fetchData} handleReset={this.handleReset}/>
</Fragment>
);
}
}
const StyledBatchFlights = withStyles(styles)(BatchFlights);
export default StyledBatchFlights;
MainContent
import React, { Component, Fragment } from 'react';
import CssBaseline from '#material-ui/core/CssBaseline';
import CSVDataTable from './CSVDataTable';
class MainContent extends Component {
render() {
return (
<Fragment>
<CssBaseline />
<main className={this.props.styles.mainPart}>
<CSVDataTable setCsvData={this.props.setCsvData} />
</main>
</Fragment>
);
}
}
export default MainContent;
CSVDataTable
import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '#material-ui/core/Button';
const sampleData = `
NUM,COL1,COL2
1,300,500
2,566,VL
`;
class CSVDataTable extends Component {
state={
csvData: sampleData
};
handleFiles = files => {
var reader = new FileReader();
reader.onload = (e) => {
// Use reader.result
this.setState({
csvData: reader.result
})
this.props.setCsvData(reader.result)
}
reader.readAsText(files[0]);
}
render() {
return <div>
<ReactFileReader
multipleFiles={false}
fileTypes={[".csv"]}
handleFiles={this.handleFiles}>
<Button
variant="contained"
color="primary"
>
Load data
</Button>
</ReactFileReader>
<CsvToHtmlTable
data={this.state.csvData || sampleData}
csvDelimiter=","
tableClassName="table table-striped table-hover"
/>
</div>
}
}
export default CSVDataTable;
But when csvData arrives to Django backend, it's empty:
csvData = request.GET.get('csvData')
print("CSV DATA",csvData) # IT IS EMPTY!!!
I believe the problem is you're trying to coerce the array csvData into a string and attach the stringified array as a parameter to your get request fetchData
'&csvData='+this.state.csvData;
If the value of csvData is made up of arrays within an array, when you coerce the array into a string through you get:
'' + [[], [], []] // "[object Object]"
If you want to keep your current get function you should instead do
'&csvData='+JSON.stringify(this.state.csvData);
but it is highly recommended that you change the get request a post or put request if you are dealing with highly nested JSON objects.