1

I was trying to set my value in the input value! but after that, I cannot write anything in the input field! I wanted to set values from the back end in value!

We are writing an admin channel to edit the article for that we need already existing article values to edit the article! What am I doing wrong! or Maybe you can suggest a better way to edit the article in the admin channel!

here is the code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useParams } from 'react-router';

const EditArticle = (props) => {
  const [editValues, setEditValues] = useState([]);
  const [changedValues, setChangedValues] = useState('');
  console.log('values', editValues);
  console.log('changed', changedValues);
  const params = useParams();
  console.log(params);
  const resultsId = params.id;
  console.log('string', resultsId);
  const [authTokens, setAuthTokens] = useState(
    localStorage.getItem('token') || ''
  );

  const setTokens = (data) => {
    localStorage.setItem('token', JSON.stringify(data));
    setAuthTokens(data);
    // setToken(data['dataValues']['token']);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get(
          `${process.env.REACT_APP_API_URL}/article/${resultsId}`
        );
        setEditValues(res.data);
      } catch (err) {}
    };
    fetchData();
  }, [resultsId]);

  const inputValue = editValues;

  const userToken = props.token;
  return (
    <div>
      <form value={{ authTokens, setAuthTokens: setTokens }}>
        <input
          value={editValues.title || ''}
          onChange={(input) => setChangedValues(input.target.value)}
          type='text'
        />
        <input
          //   ref={editValues.shortDesc}
          value={editValues.shortDesc}
          onChange={(input) => setChangedValues(input.target.value)}
          type='text'
        />
        <button type='submit'>send</button>
      </form>
    </div>
  );
};

export default EditArticle;
3
  • Your input values seem to only ever be updated when the route params update and the useEffect fetches and calls setEditValues with the response. Your onChange handler is updating state that is never used. Commented Apr 30, 2021 at 8:29
  • but I need to have the articles' old values edit with a new one! i need to edit the article! do you know better ways to do that ? Commented Apr 30, 2021 at 8:31
  • What does that even mean? Can you provide clearer explanation of desired behavior? At face value of the question "How to have changeable values in input React JS?" the answer is to pair the input's value with what the onChange handler is updating. This is how controlled inputs work. If you need different behavior then you need to explain this in more detail. Perhaps provide a set of steps you want to happen. Commented May 1, 2021 at 19:42

2 Answers 2

1

your onChange handler is updating a different state property than what is being used as the value on the input (editValues vs changedValues).

Also you can pass a defaultValue to input that will get used as the default value only.

See more here https://reactjs.org/docs/uncontrolled-components.html

Sign up to request clarification or add additional context in comments.

1 Comment

I need to have the existing default value because the admin is editing the article! so he needs a changeable value that doesn't work with defaultValue!
1

you can use just do it just using editValues. try this: I just reproduced it without the api call to run the code.

import React, { useState, useEffect } from "react";

const EditArticle = (props) => {
  const [editValues, setEditValues] = useState([]);
  console.log("values", editValues);
 
  const [authTokens, setAuthTokens] = useState(
    localStorage.getItem("token") || ""
  );

  const setTokens = (data) => {
    localStorage.setItem("token", JSON.stringify(data));
    setAuthTokens(data);
    // setToken(data['dataValues']['token']);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        //here get the data from api and setstate
        setEditValues({ title: "title", shortDesc: "shortDesc" });
      } catch (err) {}
    };
    fetchData();
  }, []);
  return (
    <div>
      <form value={{ authTokens, setAuthTokens: setTokens }}>
        <input
          value={editValues.title || ""}
          onChange={(input) => setEditValues({title: input.target.value})}
          type="text"
        />
        <input
          value={editValues.shortDesc}
          onChange={(input) => setEditValues({shortDesc: input.target.value})}

          type="text"
        />
        <button type="submit">send</button>
      </form>
    </div>
  );
};
export default EditArticle;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.