I am working with Reactjs and i am using nextjs,Right now i am trying to Post Form data But Unable to get any response(even anything in console.log),I tried with following code in index.js but nothing works,Thank you in advance
import { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import { useEffect, useState } from "react";
import styles from "../styles/Home.module.css";
import Link from 'next/link'
import Script from 'next/script'
import ReactDOM from 'react-dom';
import axios from "axios";
//const Home: NextPage = () => {
const Home = () => {
const [state, setState] = useState({
name: "",
job: ""
});
const handleChange = (e) => {
console.log('Om Success')
const value = e.target.value;
setState({
...state,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Om Success");
const userData = {
name: state.name,
job: state.job
};
axios.post("https://xxxxxxx.com/api/users", userData).then((response) => {
console.log(response.status);
console.log(response.data);
});
};
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={state.name}
onChange={handleChange}
/>
</label>
<label htmlFor="job">
Job
<input
type="text"
name="job"
value={state.job}
onChange={handleChange}
/>
</label>
<button type="submit">Register</button>
</form>
</>
);
};
export default Home;
you can post axios data by using FormData() like:
const formData= new FormData();
And then add the fields to the form you want to send:
formData.append('name', state.name);
formData.append('job', state.job);
axios({
method: "post",
url: "your url",
data: formData,
}).then((response) => {
console.log(response.status);
console.log(response.data);
});
Related
I'm new to react so pardon any mistake.
I want to update user profile picture but i dont know how can i make a clickable image(variable name ->"avatar" in code) which previews and then update(in database also), if we click save.
Can someone help me adding a clickable image that previews and updates the from and database as well.
If we cannot make clickable image, a separate button for upload and save will also be fine.
Let me know if you want more info about code.
the code i have:
import React from 'react';
import ProfileBanner from '../ProfileBanner';
import coverSrc from 'assets/img/generic/4.jpg';
//import avatar from 'assets/img/team/2.jpg';
import { Col, Row } from 'react-bootstrap';
import ProfileSettings from './ProfileSettings';
//import ExperiencesSettings from './ExperiencesSettings';
//import EducationSettings from './EducationSettings';
//import AccountSettings from './AccountSettings';
import BillingSettings from './BillingSettings';
import ChangePassword from './ChangePassword';
import DangerZone from './DangerZone';
import axios from 'axios';
import Cookies from 'universal-cookie';
import { useEffect ,useState,useRef} from 'react';
import { toast } from 'react-toastify';
const Settings = () => {
const [formData, setFormData] = useState({
avatar: '',
});
//const { avatar} = formData;
const cookies = new Cookies();
const user_id = cookies.get('xyz');
useEffect(async () => {
//e.preventDefault();
const config = {
headers: {
"Content-Type": "application/json",
},
};
try {
const { data } = await axios.post(
`/api/auth/ImageRetrieve`,
{
user_id
},
config
);
setFormData({
avatar:data.link
});
}
catch (error) {
toast.success('Something went wrong', {
theme: 'colored'
});
}
}, []);
return (
<>
<ProfileBanner>
<div>
<ProfileBanner.Header
coverSrc={coverSrc}
avatar={formData.avatar}
className="mb-8"
/>
</div>
</ProfileBanner>
<Row className="g-3">
<Col lg={8}>
<ProfileSettings />
{/*<ExperiencesSettings />
<EducationSettings />}*/}
<br></br>
<ChangePassword />
</Col>
<Col lg={4}>
<div className="sticky-sidebar">
{/* <AccountSettings />*/}
<BillingSettings />
<DangerZone />
</div>
</Col>
</Row>
</>
);
};
export default Settings;
you can basically add onClick property to any native element, so
<span onClick={()=>{ /*put here some code that change the coverSrc state*/}}>
<ProfileBanner.Header
coverSrc={coverSrc}
avatar={formData.avatar}
className="mb-8"
/>
</span>
you can create a popup to enter new pic URL and than on-close update that state.
According to my understanding of the problem, I think you are looking something like this -
const [selectedAvatar, setSelectedAvatar] = useState();
const [formData, setFormData] = useState({
avatar: '',
});
useEffect(() => {
if (!selectedAvatar) {
setFormData({...formData, avatar: ''});
return;
}
const objectUrl = URL.createObjectURL(selectedAvatar);
//DB call to save objectUrl into the DB
setFormData({...formData, avatar: objectUrl});
return () => URL.revokeObjectURL(objectUrl);
}, [selectedAvatar]);
const onSelectFile = e => {
if (!e.target.files || !e.target.files.length) {
setSelectedAvatar('');
return;
}
setSelectedAvatar(e.target.files[0]);
}
return (
<div>
<input type='file' onChange={onSelectFile} />
{!!selectedAvatar && <div>
<ProfileBanner.Header
coverSrc={coverSrc}
avatar={formData.avatar}
className="mb-8"
/>
</div>
}
</div>
)
When I want to edit my input nothing displays and I have this error:
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components input form
But I have output in my console.log.
import axios from "axios";
import React, { useEffect } from "react";
import { useParams } from 'react-router-dom'
import { useState } from "react";
const Edituser = () => {
const { id } = useParams();
const [user, setUser] = useState({
name: "",
email: "",
password: "",
c_password: "",
role: ""
});
const { name, email, password, c_password, role } = user;
const onInputChange = e => {
setUser({ ...user, [e.target.name]: e.target.value })
};
useEffect(() => {
Updaate();
},
[]
);
const Updaate = async () => {
const response = await axios.get(`http://127.0.0.1:8000/api/edit-user/${id}`);
setUser(response.data)
console.log(response.data)
};
const Updateuser = async e => {
e.preventDefault();
await axios.put(
`http://127.0.0.1:8000/api/update-user/${id}`, user
);
};
return (
<form className="register-form">
<div className="head-register" >
<h3>register</h3>
</div>
<label htmlFor="name">Username</label>
<input name="name" onChange={e => onInputChange(e)} value={name} ></input>
<h1>hello</h1>
</form>
);
}
export default Edituser;
Nothing displays when I want to edit in React.
This is the BookForm.js it is a component that use react context api , this component return a form that contain of 3 input tag
import React, { useContext, useState } from 'react';
import { BookContext } from '../contexts/BookContext';
/* ________________________________________________________________ */
const BookForm = () => {
const { dispatch } = useContext(BookContext);
const [title, setTitle] = useState(BookContext);
const [author, setAuthor] = useState(BookContext);
const handleSubmit = (e) => {
e.preventDefault();
// console.log(title, author);
dispatch({ type: 'ADD_BOOK', book: { title, author } });
// addBook(title, author);
setTitle('');
setAuthor('');
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="book title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
<input
type="text"
placeholder="author"
value={author}
onChange={(e) => setAuthor(e.target.value)}
required
/>
<input type="submit" value="add book" />
</form>
);
};
export default BookForm;
The output is
the below codebox is BookContext.js that is a stateless function for providing book data and dispatch function and there is a useEffect hook to storing data of new books :
import React, { useReducer, createContext, useEffect } from 'react';
import { bookReducer } from '../reducers/bookReducer';
/* ________________________________________________________________ */
export const BookContext = createContext();
/* ________________________________________________________________ */
const BookContextProvider = (props) => {
const [books, dispatch] = useReducer(bookReducer, [], () => {
const localData = localStorage.getItem('books');
return localData ? JSON.parse(localData) : [];
});
useEffect(() => {
localStorage.setItem('books', JSON.stringify(books));
localStorage.getItem('books');
}, [books]);
/* ________________________________________________________________ */
return (
<BookContext.Provider value={{ books, dispatch }}>
{props.children}
</BookContext.Provider>
);
};
export default BookContextProvider;
Okay I'm trying to use global states to store if an user is logged in or not. To do so, I've created a Context file as follows:
import { createContext } from "react";
export const LoginContext= createContext({})
I also have my App.jsx:
import React, { useState } from 'react';
import Component1 from './Component1.jsx';
import Component2 from './Component2.jsx';
import Component3 from './Component3.jsx';
import { LoginContext } from '../Helper/Context.js';
function App(){
const [loggedIn, setLoggedIn] = useState(false);
return (
<LoginContext.Provider value={{loggedIn, setLoggedIn}}>
<Component1 />
<Component2 />
<Component3 />
</LoginContext.Provider>
)
}
export default App;
And then I have my Login component:
import React, {useState, useContext} from "react";
import Axios from 'axios';
import { Link, useHistory } from 'react-router-dom';
import { LoginContext } from "../Helper/Context";
import NavbarHome from "./NavbarHome";
function Login()
{
Axios.defaults.withCredentials = true;
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loginStatus, setLoginStatus] = useState(false);
const {loggedIn, setLoggedIn} = useContext(LoginContext);
const [error, setErrorStatus] = useState("");
let history = useHistory();
let user = {
id: null,
nombre: null,
email: null
};
const login = () => {
Axios.post('http://localhost:3001/login', {
email: email,
password: password,
}).then((response)=>{
if(!response.data.auth) {
setLoginStatus(false);
setErrorStatus(response.data.message)
setLoggedIn(false);
}
else{
localStorage.setItem("token", response.data.token)
user = {
id: response.data.result[0].id,
name: response.data.result[0].name,
email: response.data.result[0].email
}
setLoginStatus(true);
setLoggedIn(true);
history.push('/perfil');
}
});
};
const userAuthenticated = () => {
Axios.get("http://localhost:3001/isUserAuth", {
headers: {
"x-access-token": localStorage.getItem("token"),
},
}).then((response) => {
console.log(response);
});
}
return(
<div>
<div>
<NavbarHome />
<div>
<div>
<h1>Login</h1>
<p className="label-login">Email:</p>
<input type="text" placeholder="Email..." onChange={(event) => {setEmail(event.target.value);}}/>
<p className="label-login">ContraseƱa:</p>
<input type="password" placeholder="Password..." onChange={(event) => {setPassword(event.target.value);}}/> <br />
<button onClick={login}>Login</button>
<p style={{marginTop: '1.3rem', color: 'red'}}>{error}</p>
<p><Link to='/registro'>Register here!</Link></p>
</div>
</div>
</div>
</div>
);
}
export default Login;
The output that I receive is this:
It complains about the line where I do this: setLoggedIn(false); or setLoggedIn(true); I'd like to use that state instead of setLoginStatus (which is the one I'm currently using)
Any ideas on how to fix it?
I have a problem uploading a file that is a picture for a user profile in my user collection in strapi.
This is my photo form in react
import React, {useState} from 'react';
import {Form, Button} from "semantic-ui-react"
import {useFormik} from "formik";
import * as Yup from "yup";
import {toast} from "react-toastify";
import {updatePhotoApi} from "../../../api/user";
export default function ChangeNameForm(props){
const {user, logout,setReloadUser} = props;
const [loading, setLoading] = useState(false);
const formik = useFormik({
initialValues: initialValues(user.photo),
validationSchema: Yup.object(validationSchema()),
onSubmit: async (formData) => {
console.log(formData);
setLoading(true);
const response = await updatePhotoApi(user.id, formData,logout);
console.log(response);
if(!response) {
toast.error("Error al actualizar foto ")
}else{
setReloadUser(true);
toast.success("Foto actualizada");
}
setLoading(false);
}
})
return (
<div className="change-name-form">
<h4>Cambia tu foto</h4>
<Form onSubmit={formik.handleSubmit}>
<Form.Group widths="equal">
<Form.Input
name="photo"
type="file"
placeholder="Tu nueva foto"
error={formik.errors.photo}
onChange={formik.handleChange}
value={formik.values.photo}/>
</Form.Group>
<Button className="submit" loading={loading}>Actualizar</Button>
</Form>
</div>
);
}
function initialValues(photo){
return {
photo: photo || "",
}
}
function validationSchema(){
return {
photo: Yup.string().required(true),
}
}
and there is the api call
export async function updatePhotoApi(idUser,data,logout){
try {
const url = `${BASE_PATH}/users/${idUser}`;
const params = {
method: "PUT",
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify(data),
};
const result = await authFetch(url,params,logout);
console.log(result);
return result ? result : null;
} catch (error) {
console.log(error);
return null;
}
}
but im still getting error 505 internal server error, i dont know what im doing wrong, and cant find such information about to do this.
In my collection for user i have the field called photo for the a single img picture, for later show it as a avatar picture in the client