I'm trying to figure out how to add data to cloud firestore from my react app.
I have it all working for the data entered in a form, but am missing something because when I try to add a createdAt timestamp, I get an error.
My current attempt is:
import React from "react";
import { Link } from 'react-router-dom'
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";
import { fsDB, firebase, settings } from "../../../firebase";
const Result = props => {
const { state } = {
useStateMachine(updateAction),
createdAt: firebase.firestore.FieldValue.serverTimestamp()
};
fsDB
.collection("project")
.add(state)
return (
<div>
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
);
};
export default Result;
If i remove the createdAt and just upload state, it all works fine.
I'm getting stuck on how to add the timestamp.
Can anyone see where I'm going wrong?
I have found this post which sets out a snap shot to merge a date field with a record. I'm struggling to understand if there is something about snapshot which needs the record to be created before a date can be added? It doesn't seem logical that I have to create a record before I can merge a date field into it.
Related
I'm learn from projects Javascript Everywhere book. I have a problem when i'm doing delete (mutation) action. in the Backend, Delete Mutation works normally. But in the front end. let's say i'm have 2 pages that querying notes. Home and MyNotes.
Home page
My Notes Page
When i'm clicking delete note. it direct to '/mynotes' page, and delete the note. UI update normaly when i'm deleting inside mynotes page, but when i'm going to home page, notes that has been delete before is still showing.
here's my code
DeleteNote.js
import React from 'react';
import { useMutation } from '#apollo/client';
import { withRouter } from 'react-router-dom';
import ButtonAsLink from './ButtonAsLink';
import { DELETE_NOTE } from '../gql/mutation';
import { GET_MY_NOTES, GET_NOTES } from '../gql/query';
const DeleteNote = props => {
const [deleteNote] = useMutation(DELETE_NOTE, {
variables: {
id: props.noteId
},
// refetch the note list queries to update the cache
refetchQueries: [{ query: GET_MY_NOTES, GET_NOTES }],
onCompleted: data => {
// redirect the user to the "my notes" page
props.history.push('/mynotes');
},
options: {
fetchPolicy: 'cache-first',
errorPolicy: 'ignore'
}
});
return <ButtonAsLink onClick={deleteNote}>Delete Note</ButtonAsLink>;
};
export default withRouter(DeleteNote)
;
delete mutation
const DELETE_NOTE = gql`
mutation deleteNote($id: ID!) {
deleteNote(id: $id)
}
`;
i want to delete note in homepage with realtime results. i don't have any idea , i'm beginner in graphQL. any help will be appreciated, thank you.
import React, { useState ,useEffect} from 'react';
import { Link ,useHistory,useParams} from 'react-router-dom';
import { getDatabase,ref, child, get } from 'firebase/database';
import { auth, db } from './Config/Config';
export default function User()
const [user,setUser]=useState()
const {id}=useParams();
const dbRef = ref(getDatabase());
get(child(dbRef, AllUsers/${id})).then((snapshot) => {
if (snapshot.exists()) {
setUser(...snapshot.val());
} else {
console.log('user',user)
return (
{id}
</div>
)
}
IDK how to use that firebase id tho but if want to show data getting as responses then you already store firebase data in the local-state now you can use that state to get data and show anywhere {user.id} or whatever ur getting in response!
It's a design pattern using lowercase as params. So rename to allusers or all-users.
Are you sure you getting the right ID from params ?
also, paste your full code pls.
I am having a problem finding a way i can reliably store the state of the date from react-datepicker, and exporting that state to another component via URL parameter.
To give some context, I have two components. A Picker.JS component containing the react-datepicker calendar, and a separate Component called "DelayGuage", which dynamically draws a google charts guage using an API call. The only problem is, this API call has a dynamic parameter known as {date}, and this {date} parameter MUST come from the previously selected datepicker date.
Here is my DatePicker code Below. The issue I am having is that I keep getting
"Uncaught TypeError: event.target is undefined" when I attempt to call handleSubmit() after the calendar date is selected (onSelect).
import React, { useState } from "react";
import DatePicker from "react-datepicker";
import {Link, useNavigate} from "react-router-dom"
import "react-datepicker/dist/react-datepicker.css";
// CSS Modules, react-datepicker-cssmodules.css
// import 'react-datepicker/dist/react-datepicker-cssmodules.css';
const Picker = () => {
const navigate = useNavigate();
const [startDate, setStartDate] = useState(new Date());
const handleChange = (event) => {
setStartDate(event.target.value)
console.log(startDate)
}
const handleSubmit = (event) =>{
event.preventDefault();
navigate(`/guage/${startDate}`) //upon the call of handleSubmit, a redirect should call the guage component to be rendered, taking the startDate as a URL parameter
}
return (
<DatePicker selected={startDate} onChange={(date) => setStartDate(date)} onSelect={handleChange}/>
);
};
export default Picker
The second problem, is that I need to find a way to input the date selected from the Calendar with the API call to the backend to retrieve the data for my Guage. It only fetches a JSON for now, but the ability to fetch the appropriate JSON per date selected from the Picker.JS component has been giving me a headache.
Here is my DelayGuage.JS code below:
import React from "react";
import { Chart } from "react-google-charts";
import axios from "axios";
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
import { Link, useLocation, useParams } from "react-router-dom";
async function fetchPosts() {
const {data} = await axios.get(
"http://172.16.10.100:5004/reports/{date}/agencies"
);
const parsedData = data.agencies[0].kpis.map((r) => [
"Delay Index",
r.kpi_value * 100
]);
return [["Label", "Value"], ...parsedData];
}
So, to summarize, there are two issues in this project. The first being a way to store the selected date in the datepicker, and the second being a way to parse said selected date in the redirect guage/'${startDate}' URL to be used directly in the API call "http://172.16.10.100:5004/reports/{date}/agencies". This will return a JSON containing the object retrieved from a database (backend has been set up already).
Your onChange does the intended behavior of storing the value of the DatePicker input in your state as startDate. Passing the onSelect prop to the <DatePicker /> causes issues as the event parameter passed in to the onSelect is actually just the updated input value (you can see this if you console.log(event)). The <DatePicker /> component is just an input component, not an entire form. You should wrap the component in a form and pass the handleSubmit to an onSubmit prop of the form. There is an example in the React Router docs for useNavigate.
For the second part of your question, look into React Router's url parameters (guide, example). You can use the useParams() hook to get the startDate from the URL, and use that in your API call.
I've been trying to display the contents of a list using JSX in React. My server side is flask and serves JSON data to the react frontend. When I provide JSON data with only a simple dictionary with string keys and values, react can display it just fine, but when I try to use a list, and I've been messing around with this for 15 hours now, it just keeps saying "Uncaught TypeError: initialData.names is undefined". This error is consistent across different mehthods of requesting the data. If I choose to display initialData.names, there is an error that JSX can't display an object with keys of "name". But as soon as I try to access the data inside, it freaks out. I've never used Stack Overflow before so let me know if my question needs a different format.
routes.py
import json as JSON
from flask import render_template, jsonify
from api import app
from api.static import variables as VARS
#app.route("/regions")
def regions():
print("REGIONS")
'''
data = {"data":[{
"name": region_name,
"url": "/regions/" + region_name
} for region_name in VARS.region_names]}
'''
'''
data = {
"name":"ford"
}
'''
data = {
"names":[{"name":"ford"},{"name":"toyota"}]
}
return data
Regions.js --gets run from the main js file
import React, {useEffect, useState} from 'react'; //ES6 js
import {Link, useParams} from 'react-router-dom'
function Regions(){
const [initialData, setInitialData] = useState([{}]);
useEffect(() => {
fetch('/regions').then(
response => response.json()
).then(
data => setInitialData(data)
)
});
return(
<div>
<h1>Select a Region</h1>
{initialData.names.map(brand => (<h2>{brand.name}</h2>))}
</div>
);
}
export default Regions;
Js Error
I am working in React, and I have a mutation that will be called essentially the exact same way across a multitude of different files. Rather than type the same syntax over and over, I attempted to make a hook file that would carry out the process, and I could just import it and call it from inside the many components that need this mutation. However, I am hitting the following error...
React Hook "useMutation" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
The error is clear enough, I can see what the issue is, but I have no idea how to create a custom React Hook Function and the site to which the direct me to is not particularly helpful. Would someone be able to explain to me how to make this file a 'react hook?'
import React from "react";
import { useMutation } from "#apollo/client";
import { MANAGER_REFRESH, OWNER_REFRESH } from "../../graphql/operations";
const [managerRefresh, { loading: loadingM, error: errorM, data: dataM}] = useMutation(MANAGER_REFRESH)
const [ownerRefresh, { loading: loadingO, error: errorO, data: dataO}] = useMutation(OWNER_REFRESH)
const refresh = async (role, userId) => {
if (role === "MANAGER"){
return await managerRefresh({
variables: {
role: role,
id: userId
}
})
}
else if (role === "OWNER"){
return await ownerRefresh({
variables: {
role: role,
id: userId
}
})
}
}
export default refresh