How to show submitted data in React immediately, without refreshing the page? - javascript

I'm building a simple note-taking app and I'm trying to add new note at the end of the list of notes, and then see the added note immediately. Unfortunately I'm only able to do it by refreshing the page. Is there an easier way?
I know that changing state would usually help, but I have two separate components and I don't know how to connect them in any way.
So in the NewNoteForm component I have this submit action:
doSubmit = async () => {
await saveNote(this.state.data);
};
And then in the main component I simply pass the NewNoteForm component.
Here's the whole NewNoteForm component:
import React from "react";
import Joi from "joi-browser";
import Form from "./common/form";
import { getNote, saveNote } from "../services/noteService";
import { getFolders } from "../services/folderService";
class NewNoteForm extends Form {
//extends Form to get validation and handling
state = {
data: {
title: "default title",
content: "jasjdhajhdjshdjahjahdjh",
folderId: "5d6131ad65ee332060bfd9ea"
},
folders: [],
errors: {}
};
schema = {
_id: Joi.string(),
title: Joi.string().label("Title"),
content: Joi.string()
.required()
.label("Note"),
folderId: Joi.string()
.required()
.label("Folder")
};
async populateFolders() {
const { data: folders } = await getFolders();
this.setState({ folders });
}
async populateNote() {
try {
const noteId = this.props.match.params.id;
if (noteId === "new") return;
const { data: note } = await getNote(noteId);
this.setState({ data: this.mapToViewModel(note) });
} catch (ex) {
if (ex.response && ex.response.status === 404)
this.props.history.replace("/not-found");
}
}
async componentDidMount() {
await this.populateFolders();
await this.populateNote();
}
mapToViewModel(note) {
return {
_id: note._id,
title: note.title,
content: note.content,
folderId: note.folder._id
};
}
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
doSubmit = async () => {
await saveNote(this.state.data);
};
render() {
return (
<div>
<h1>Add new note</h1>
<form onSubmit={this.handleSubmit}>
{this.renderSelect("folderId", "Folder", this.state.folders)}
{this.renderInput("title", "Title")}
{this.renderInput("content", "Content")}
{this.renderButton("Add")}
</form>
</div>
);
}
}
export default NewNoteForm;
And here's the whole main component:
import React, { Component } from "react";
import { getNotes, deleteNote } from "../services/noteService";
import ListGroup from "./common/listGroup";
import { getFolders } from "../services/folderService";
import { toast } from "react-toastify";
import SingleNote from "./singleNote";
import NewNoteForm from "./newNoteForm";
class Notes extends Component {
state = {
notes: [], //I initialize them here so they are not undefined while componentDidMount is rendering them, otherwise I'd get a runtime error
folders: [],
selectedFolder: null
};
async componentDidMount() {
const { data } = await getFolders();
const folders = [{ _id: "", name: "All notes" }, ...data];
const { data: notes } = await getNotes();
this.setState({ notes, folders });
}
handleDelete = async note => {
const originalNotes = this.state.notes;
const notes = originalNotes.filter(n => n._id !== note._id);
this.setState({ notes });
try {
await deleteNote(note._id);
} catch (ex) {
if (ex.response && ex.response.status === 404)
toast.error("This note has already been deleted.");
this.setState({ notes: originalNotes });
}
};
handleFolderSelect = folder => {
this.setState({ selectedFolder: folder }); //here I say that this is a selected folder
};
render() {
const { selectedFolder, notes } = this.state;
const filteredNotes =
selectedFolder && selectedFolder._id //if the selected folder is truthy I get all the notes with this folder id, otherwise I get all the notes
? notes.filter(n => n.folder._id === selectedFolder._id)
: notes;
return (
<div className="row m-0">
<div className="col-3">
<ListGroup
items={this.state.folders}
selectedItem={this.state.selectedFolder} //here I say that this is a selected folder
onItemSelect={this.handleFolderSelect}
/>
</div>
<div className="col">
<SingleNote
filteredNotes={filteredNotes}
onDelete={this.handleDelete}
/>
<NewNoteForm />
</div>
</div>
);
}
}
export default Notes;
How can I connect these two components so that the data shows smoothly after submitting?

You can use a callback-like pattern to communicate between a child component and its parent (which is the 3rd strategy in #FrankerZ's link)
src: https://medium.com/#thejasonfile/callback-functions-in-react-e822ebede766)
Essentially you pass in a function into the child component (in the main/parent component = "Notes": <NewNoteForm onNewNoteCreated={this.onNewNoteCreated} />
where onNewNoteCreated can accept something like the new note (raw data or the response from the service) as a parameter and saves it into the parent's local state which is in turn consumed by any interested child components, i.e. ListGroup).
Sample onNewNoteCreated implementation:
onNewNoteCreated = (newNote) => {
this.setState({
notes: [...this.state.notes, newNote],
});
}
Sample use in NewNoteForm component:
doSubmit/handleSubmit = async (event) => {
event.preventDefault();
event.stopPropagation();
const newNote = await saveNote(this.state.data);
this.props.onNewNoteCreated(newNote);
}
You probably want to stop the refresh of the page on form submit with event.preventDefault() and event.stopPropagation() inside your submit handler (What's the difference between event.stopPropagation and event.preventDefault?).

Related

Redux props logging incorrect data

Right now I am trying to console.log this.streamCreatorUid, but I'm running into a peculiar issue. In my redux debugger, I can clearly see my data in the proper place.
Here is my redux data for the stream creator, directly from my debugger.
streams -
[0] -
{category(pin): "Oldschool Runescape"
displayName(pin): "admin"
streamId(pin): "98ebc719-c7d5-4558-b99d-2d9f8306ec64"
title(pin): "accounttest"
uid(pin): "wsFc7pIMq5dMtw9hPU86DzUTdLO2"
}
I am trying to console.log this.streamCreatorUid from my mapstatetoprops, but it is returning the current user Uid of u9TcrICehNMlAmqyDHQY77L9CXq1 instead. I'm quite confused as to why this is happening, considering this is not the data shown in my debugger.
This is for a personal project. In the past I've accessed redux props like this with no issues, now I'm not quite sure why this is happening.
import React from 'react';
import { database } from '../../../firebaseconfig.js';
import { connect } from 'react-redux';
class StreamFollow extends React.Component {
constructor(props) {
super(props);
this.uid = this.props.uid;
this.displayName = this.props.displayName;
this.streamCreatorUid = this.props.streamCreatorUid;
this.streamCreatorDisplayName = this.props.streamCreatorDisplayName;
}
componentShouldUpdate(prevProps) {
if (this.props.uid !== prevProps.uid) {
this.uid = this.props.uid
}
if (this.props.streamCreatorUid !== prevProps.streamCreatorUid) {
this.streamCreatorUid = this.props.streamCreatorUid;
}
}
//creates a follower object under the stream creators uid
createFollower = (e) => {
const followerRef = database.ref(`User_Follow_Info/${e}/Follower`)
const followerInfoObject = {
uid: this.uid,
displayName: this.displayName
}
followerRef.push(followerInfoObject);
}
//creates a following object under the users uid
//Add in checks to see if following object already exists. We can't follow someone multiple times
createFollowing = (user) => {
const followingRef = database.ref(`User_Follow_Info/${user}/Following`);
const followingInfoObject = {
uid: this.streamCreatorUid,
displayName: this.streamCreatorDisplayName
}
console.log(this.streamCreatorDisplayName)
//Check to see if follow already exists.
/*followingRef.once('value', function (snapshot) {
if (snapshot.hasChild(DATA HERE)) {
alert('exists');
}
}); */
var isSignedIn = this.isSignedIn;
followingRef.orderByChild('uid').equalTo(this.uid).once('value').then(snapshot => {
console.log(snapshot.val());
console.log(this.streamCreatorUid);
if (isSignedIn) {
console.log(snapshot.val())
return
} else {
followingRef.push(followingInfoObject);
}
})
}
onSubmit = () => {
if (this.props.isSignedIn === true) {
this.createFollowing(this.uid);
this.createFollower(this.streamCreatorUid);
} else {
//add in a sign in modal if user is not logged in
console.log('please sign in')
}
}
render() {
return (
<div>
<button onClick={this.onSubmit}>Follow</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
isSignedIn: state.auth.isSignedIn,
displayName: state.auth && state.auth.userInfo ? state.auth.userInfo.displayName : null,
uid: state.auth && state.auth.userInfo ? state.auth.userInfo.uid : null,
streamCreatorUid: state.streams && state.streams[0] ? state.streams[0].uid : null,
streamCreatorDisplayName: state.streams && state.streams[0] ? state.streams[0].displayName : null,
}
}
export default connect(mapStateToProps)(StreamFollow);

React: Static method always returns undefined

I have a problem with a static method in React using ESLint with airbnb config. I have a service like this that is both used for creating a user in my system, and getting all the field values for the create user form. The service looks like this:
import axios from 'axios';
import ServiceException from './ServiceException';
class CreateUserServiceException extends ServiceException {}
class CreateUserService {
constructor(config) {
this.apiUrl = config.API_URL;
this.userDomain = config.USER_DOMAIN;
}
static getFormFields() {
return [
{
id: 'username',
type: 'text',
title: 'E-postadress',
placeholder: 'Användarnamn',
mandatory: true,
extra: '',
},
{
id: 'password',
type: 'password',
title: 'Lösenord',
placeholder: 'Lösenord',
mandatory: true,
extra: '',
},
];
}
async createUser(data) {
try {
await axios.post(`${this.apiUrl}/users/${this.userDomain}`, data, { withCredentials: true });
} catch ({ response }) {
throw new CreateUserServiceException(
response.status, 'Failed to create user', response.data,
);
}
}
}
export default CreateUserService;
I also have a jsx controller to create my form. This controller gets the service via it's properties. The controller looks like this:
import React from 'react';
import './index.css';
class CreateUserController extends React.Component {
constructor(props) {
super(props);
this.state = {
formFields: [],
userData: {},
};
this.onCreate = this.onCreate.bind(this);
this.onLoad = this.onLoad.bind(this);
}
async componentDidMount() {
await this.onLoad();
}
async onLoad() {
const { createUserService } = await this.props;
const { getFormFields } = createUserService;
const formFields = getFormFields || []; // ALWAYS RETURNS UNDEFINED
const userData = {};
console.log(formFields); // ALWAYS DISPLAYS []
formFields.forEach((field) => {
userData[field.id] = '';
});
this.setState({ formFields, userData });
}
async onCreate(e) {
e.preventDefault();
const { userData } = this.state;
console.log(userData);
}
render() {
const { userData, formFields } = this.state;
return (
<section className="create-user-controller">
<h1>Skapa ny användare</h1>
<form
className="centered-container"
action=""
noValidate
onSubmit={this.onCreate}
>
<table>
<tbody>
{formFields.map(field => (
<tr key={field.id}>
<td>{field.title}</td>
<td>
<input
value={userData[field.id]}
onChange={e => this.setState({
userData: { ...userData, [field.id]: e.target.value },
})}
className={`create-${field.id}`}
name={field.id}
placeholder={field.placeholder}
type={field.type}
/>
</td>
<td>{field.extra}</td>
</tr>
))}
<tr>
<td colSpan={3}>* obligatoriskt</td>
</tr>
</tbody>
</table>
<input type="submit" className="btn btn-green" value="Skapa användare" />
</form>
</section>
);
}
}
export default CreateUserController;
My problem is that const formFields = getFormFields || []; always becomes [] which means that getFormFields always returns undefined.
If I remove static from getFormFields() in my service and call it using const formFields = createUserService.getFormFields(); it works fine, but then ESLint complains about ESLint: Expected 'this' to be used by class method 'getFormFields'. (class-methods-use-this).
Does anyone have an idea how to solve this?
import CreateUserService from './CreateUserService';
...
async onLoad() {
...
const formFields = CreateUserService.getFormFields() || [];
...
}
Should do the trick !
Notice that the static function is called using the Class name. Tou will also have to import it correctly (i don't know your path…)

React State Storing & Outputting Duplicate Values

Slight issue here which I think is relatively simple to solve but I can't quite get my head around. I'm quite new to React. I've decided to make a small sample app which just takes the input from two fields, saves them to Firebase and outputs those values on the page. It works completely fine in terms of submitting data and retrieving it, but when I click the submit button to add the data to Firebase it seems to duplicate the data stored in the state and render them twice:
Parent Component:
import React, { Component, Fragment } from 'react';
import firebase from '../../config/firebase';
import QuestFormField from './QuestFormField/QuestFormField';
import QuestFormSelection from './QuestFormSelection/QuestFormSelection';
import classes from './QuestForm.css';
class QuestForm extends Component {
state = {
value: '',
points: 0,
items: []
}
questHandler = e => {
this.setState({
value: e.target.value,
});
}
pointsHandler = e => {
this.setState({
points: e.target.value,
});
}
submitHandler = e => {
e.preventDefault();
const itemsRef = firebase.database().ref('quest');
const items = {
quest: this.state.value,
points: this.state.points
}
itemsRef.push(items);
this.setState({
value: '',
points: 0
});
}
render () {
return (
<Fragment>
<form className={classes.Form} onSubmit={this.submitHandler}>
<QuestFormField val='Quest' inputType='text' name='quest' value={this.state.value} changed={this.questHandler} />
<QuestFormField val='Points' inputType='number' name='points' value={this.state.points} changed={this.pointsHandler} />
<button>Away! To Firebase!</button>
</form>
<QuestFormSelection />
</Fragment>
);
}
}
export default QuestForm;
Child Component (Form Fields)
import React from 'react';
import classes from './QuestFormField.css';
const QuestFormField = (props) => (
<div className={classes.Container}>
<label htmlFor={props.name}>{props.val}</label>
<input type={props.inputType} name={props.name} onChange={props.changed}/>
</div>
);
export default QuestFormField;
Child Component B (Data Retriever/Displayer)
import React, { Component, Fragment } from 'react';
import firebase from '../../../config/firebase';
import classes from './QuestFormSelection.css';
class QuestFormSelection extends Component {
state = {
quests: []
}
componentDidMount() {
const database = firebase.database();
const quests = [];
database.ref('quest').on('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
quests.push({
id: childSnapshot.key,
quest: childSnapshot.val().quest,
points: childSnapshot.val().points,
});
});
console.log(quests);
this.setState(() => {
return {
quests: quests
}
});
console.log(this.state.quests);
});
}
render () {
return (
<section className='display-item'>
<div className="wrapper">
{this.state.quests.map(quest => (
<div key={quest.key}>
<p>{quest.quest}</p>
<p>{quest.points}</p>
</div>
))}
</div>
</section>
)
}
}
export default QuestFormSelection;
Example of behaviour here:
https://i.gyazo.com/c70972f8b260838b1673d360d1bec9cc.mp4
Any pointers would help :)
I haven't used firebase myself, but it looks like the code below is setting up a listener to "quest" changes which will execute each time a change occurs, but you defined const quests = [] outside of the db change handler. This means that on the second change, you will push everything in the snapshot to the same quests array that may have already had previous snapshots added to it. I believe you can fix this by moving the quests variable inside the listener function as shown below.
componentDidMount() {
const database = firebase.database();
database.ref('quest').on('value', (snapshot) => {
const quests = [];
snapshot.forEach((childSnapshot) => {
quests.push({
id: childSnapshot.key,
quest: childSnapshot.val().quest,
points: childSnapshot.val().points,
});
});
console.log(quests);
this.setState(() => {
return {
quests: quests
}
});
console.log(this.state.quests);
});
}

React.js moving on to the next list

I'm making a movie search page. When I search something, it goes through the data base and find the very first match and display on the page. However, I want to create a function, so when I click next, page displays next movie in the data base. My code follows:
import React, { Component, PropTypes } from 'react';
import SearchBar from './Bar/index.js';
import SearchResult from './Result/index.js';
import axios from 'axios';
import './index.css';
class SearchArea extends Component {
constructor(props) {
super(props);
this.state = {
searchText: '',
searchResult: {},
result: false,
count: 0
};
}
handleSearchBarChange(event) {
this.setState({searchText: event.target.value});
}
handleSearchBarSubmit(event) {
event.preventDefault();
const movie = this.state.searchText;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=c6cd73ec4677bc1d7b6560505cf4f453&language=en-US&query=${movie}&page=1&include_adult=false`)
.then(response => {
if(response.data.results.length >= 0) {
const i = 0;
const {
title,
overview,
release_date: releaseDate
} = response.data.results[this.state.count];
const posterPath = 'https://image.tmdb.org/t/p/w154' + response.data.results[this.state.count].poster_path;
this.setState({
searchResult: {
title,
posterPath,
overview,
releaseDate
},
result: true
});
}
else {
this.setState({
searchResult: {
title: 'No Result',
overview: 'No Overview Available',
posterPath: ''
},
result: true
});
}
})
}
handleSearchNext(event) {
this.handelSearchBarSubmit.overview = response.data.results[1];
}
handleResultClose() {
this.setState({
searchResult: {},
result: false
});
}
render() {
return (
<div>
<SearchBar
value = {this.state.searchText}
onChange = {this.handleSearchBarChange.bind(this)}
onSubmit = {this.handleSearchBarSubmit.bind(this)}
onNext = {this.handleSearchNext.bind(this)}
/>
{this.state.result &&
<SearchResult
searchResult = {this.state.searchResult}
onClose = {this.handleResultClose.bind(this)}
onAdd = {this.props.onAdd}
/>
}
</div>
);
}
}
SearchArea.propTypes = {
onAdd: PropTypes.func.isRequired
};
export default SearchArea;
I can't seem to figure out how to make handleSearchNext. Please help
EDIT
Following is the SearchBar code
import React, { PropTypes } from 'react';
import { Button } from 'semantic-ui-react';
import styles from './index.css';
const SearchBar = (props) => {
return (
<div>
<form onSubmit={(event) => props.onSubmit(event)}>
<input
className="searchBar"
type="text"
placeholder="Search Here"
value={props.value}this
onChange={(event) => props.onChange(event)}
onNext={(event) => props.onChange(event)}
onBack={(event) => props.onChange(event)}
/>
<Button className="button" type="submit">Sumbit</Button>
</form>
<Button className={styles.button} type="previous">Back</Button>
<Button className="button" type="next">Next</Button>
</div>
);
};
SearchBar.propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired,
onNext: PropTypes.func.isRequired
};
export default SearchBar;
You could have your server respond with not only the requested title, but also the next one. That way, when you click on Next, you can immediately display the next movie without waiting for a response, while still querying it in the background by name or id (so that you have the next after it, etc.).
Edit: If I misunderstood what you meant and you already have this (it looks like you are actually querying a whole page of movies at once), you probably simply want something like
handleSearchNext(event) {
this.setState({ searchResult: response.data.results[1], result: true });
}
and handle specially the case when you hit the last item on the page.

Relay Error when deleting: RelayMutationQuery: Invalid field name on fat query

I'm running into an issue when I attempt to commit a deletion mutation. When I commit, I get the error Uncaught Invariant Violation: RelayMutationQuery: Invalid field name on fat query, `company`.. Viewing, creating and updating nodes all work. For some reason I just can't delete. It mentions the company field in the fatQuery, but the only field I have in the fat query is the deletedUserId I get back from the server. Thanks in advance!
Component:
import React, {Component} from 'react';
import Relay from 'react-relay';
import {Link} from 'react-router';
import DeleteUserMutation from 'mutations/DeleteUserMutation';
import styles from './EmployeeItem.css';
class EmployeeItem extends Component {
render() {
const {user} = this.props;
return (
<div className={styles.employee}>
<p><strong>ID:</strong> {user.id}</p>
<p><strong>First Name:</strong> {user.firstName}</p>
<p><strong>Last Name:</strong> {user.lastName}</p>
<p><strong>Email:</strong> {user.email}</p>
<div className="btn-group">
<Link to={`/company/employees/${user.id}`} className="btn btn-primary">View Employee</Link>
<button onClick={this.handleRemove} className="btn btn-danger">Delete User</button>
</div>
</div>
)
}
handleRemove = (e) => {
e.preventDefault();
const {user, company} = this.props;
Relay.Store.commitUpdate(new DeleteUserMutation({user, company}));
};
}
export default Relay.createContainer(EmployeeItem, {
fragments: {
company: () => Relay.QL`
fragment on Company {
id
${DeleteUserMutation.getFragment('company')}
}
`,
user: () => Relay.QL`
fragment on User {
id
firstName
lastName
email
${DeleteUserMutation.getFragment('user')}
}
`
}
});
Mutation:
import React from 'react';
import Relay from 'react-relay';
export default class DeleteUserMutation extends Relay.Mutation {
static fragments = {
company: () => Relay.QL`
fragment on Company {
id
}
`,
user: () => Relay.QL`
fragment on User {
id
}
`
};
getMutation() {
return Relay.QL`mutation {deleteUser}`;
}
getFatQuery() {
return Relay.QL`
fragment on DeleteUserPayload {
deletedUserId
}
`;
}
getVariables() {
return {
id: this.props.user.id,
}
}
getConfigs() {
return [{
type: 'NODE_DELETE',
parentName: 'company',
parentID: this.props.company.id,
connectionName: 'employees',
deletedIDFieldName: 'deletedUserId'
}]
}
// Wasn't sure if this was causing the error but it appears to be
// something else.
// getOptimisticResponse() {
// return {
// deletedUserId: this.props.user.id
// }
// }
}
This error is referring to the fact that you reference the "company" in your getConfigs() implementation. The NODE_DELETE config tells Relay how to construct the mutation query by mapping nodes in the store (e.g. parentID) to fields on the fat query (e.g. parentName).
Although you might not necessarily need it today, you should add the company to the mutation payload & fat query here, since the company is being affected by this change. More specifically, the company's employees connection is being modified :)
NevilleS' solution solved it for me:
I added a globalId to the root field (in my case an object called "verify") and I also changed my mutation on the server to return an edge, rather than just the underlying type. I also added the root "verify" object to the mutation output fields: it would make sense that the client's relay mutation needs that to know which object owns the connection, where to put the new edge.
export const Verify = new GraphQLObjectType({
name: 'Verify',
fields: () => ({
id: globalIdField('Verify'),
verifications: {
args: connectionArgs,
type: VerificationConnection,
resolve: (rootValue, args) => connectionFromArray(rootValue.verifications, args)
},
Adding "verify" and "verificationEdge" to the mutation's output fields.
export const AddVerifiedSchool = mutationWithClientMutationId({
name: 'AddVerifiedSchool',
inputFields: {
verification: {
type: VerifiedSchoolInput
}
},
outputFields: {
success: {
type: GraphQLBoolean,
resolve: () => true
},
verificationEdge: {
type: VerificationEdge,
resolve: ({verification, context}) => {
console.log('verification', verification);
return verification
}
},
verify: {
type: Verify,
resolve: ({verification, context}) => {
return context.rootValue
}
}
},
Adding the verify field to the fat query, and (the globalId "id" from verify) to the fragments, and using the new globalId to identify the node where the connection exists.
static fragments = {
verify: () => Relay.QL`fragment on Verify { id }`,
action: () => Relay.QL`fragment on Action { name url }`
};
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'verify',
parentID: this.props.verify.id,
connectionName: 'verifications',
edgeName: 'verificationEdge',
rangeBehaviors: {
'': 'append'
}
}];
}
getFatQuery() {
return Relay.QL`
fragment on AddVerifiedSchoolPayload {
verification {
${VerifiedSchool.getFragment('verification')}
}
verify {
id
}
}`
}

Categories

Resources