0

I'm trying to update information from the client side with a PUT request to my Fastify server, but nothing is being sent. No Errors displaying either, just no change.

POST and GET requests work fine from the client side.

PUT requests work in Insomnia/Postman.

I have fastify-cors installed:

fastify.register(require("fastify-cors"), {
  origin: "*",
  methods: "GET,POST,PUT,PATCH,DELETE",
});

Client Side Request

export default function EditUser({ route, navigation }) {
  const { item } = route.params;
  const [firstName, setFirstName] = useState(item.name[0].firstName);

  const editUser = async () => {
    try {
      const res = await fetch(`http://<myIPaddr>:5000/api/users/${item._id}`, {
        method: "PUT",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: firstName,
      });
      console.log(firstName);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View>
      <Layout>
        <Text style={styles.text}>EDIT USER PAGE</Text>

        <View>
          <TextInput
            style={styles.input}
            onChangeText={(e) => setFirstName(e)}
            value={firstName}
          />
          <Text style={{ color: "#FFF" }}>{item._id}</Text>
          <Button title="save changes" onPress={editUser} />
        </View>
      </Layout>
    </View>
  );
}

Backend Route


  fastify.put("/:id", async (request, reply) => {
    try {
      const { id } = request.params;
      const user = await User.findByIdAndUpdate(id, request.body);
      if (!user) {
        return reply.status(400).send({ error: "couldn't find user" });
      }
      reply.status(200).send({ success: true, data: user });
    } catch (error) {
      reply.status(400).send({ error: "request failed" });
    }
  });
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Eric Pezzulo
  • 299
  • 4
  • 18

2 Answers2

0

Check the backend logs, it could be that you're using return reply.send. Remove the return. From the docs:

Warning:

When using both return value and reply.send(value) at the same time, the first one that happens takes precedence, the second value will be discarded, and a warn log will also be emitted because you tried to send a response twice.

theneekz
  • 98
  • 10
0

Found the fix, I wasn't passing the data in the right way

const editUser = async () => {
    const userEndpoint = `http:<myIPaddr>:5000/api/users`;
    try {
      const res = await axios({
        url: `${userEndpoint}/${item._id}`,
        method: "PUT",
        data: {
          name: {
            firstName: firstName,
          },
        },
      });
      console.log(firstName);
    } catch (error) {
      console.log(error);
    }
  };
Eric Pezzulo
  • 299
  • 4
  • 18