Uploading and saving data to an object in FaunaDB using React hook forms

I am currently facing an issue with uploading/saving data to an object in FaunaDB. Specifically, I am trying to upload a string to a jobProfile object:

data: {
 "jobProfile": {
    "image": ""
    "coverImage": ""
 }
}

However, when I attempt to upload the strings using the submit button, they are getting saved in the root like this:

data: {
  "image": ""
  "coverImage": ""
}

In my main component, I have integrated react-hook-forms where default values are fetched from userData obtained via useSWR through a prop:

import { useForm } from "react-hook-form"

import ImageInput from "./ImageInput"

export default function Inputs({ userData }) {
  const defaultValues = {
    image: userData?.jobProfile?.image ? userData?.jobProfile?.image : "",
    coverImage: userData?.jobProfile?.coverImage ? userData?.jobProfile?.coverImage : ""
  }

  const { register, handleSubmit } = useForm({ defaultValues })

  const handleUpdateUser = async (data) => {
    const { image, coverImage } = data
    try {
      await fetch("/api/updateProfile", {
        method: "PUT",
        body: JSON.stringify({
          image, coverImage
        }),
        headers: {
          "Content-Type": "application/json",
        },
      })
      alert(`submitted data: ${JSON.stringify(data)}`)
    } catch (err) {
      console.error(err)
    }
  }

  return (
    <form onSubmit={handleSubmit(handleUpdateUser)}>
      <div className="py-4">
        <ImageInput register={register} />
      </div>
      <button type="submit">Update</button>
    </form>
  )
}

Below is the component ImageInput.jsx imported within the main component. This component includes input fields for image and coverImage:

//ImageInput.jsx
export default function ImageInput({ register }) {
  return (
    <div className="grid gap-4">
      <div>
        <label
          htmlFor="company-website"
          className="block text-sm font-medium text-gray-700"
        >
          Profilbillede
        </label>
        <div className="relative mt-1 rounded-md shadow-sm">
          <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
            <span className="text-gray-500 sm:text-sm">https://</span>
          </div>
          <input
            type="text"
            name="company-website"
            id="company-website"
            className="block w-full rounded-md border-gray-300 pl-16 focus:border-indigo-500 focus:ring-indigo-500 sm:pl-14 sm:text-sm"
            placeholder="www.example.com/profile/avatar"
            {...register("jobProfile.image", {})}
          />
        </div>
        <p className="mt-2 text-sm text-gray-500" id="email-description">
          Indsæt billede URL (link) fra eksempelvis Facebook eller LinkedIn.
        </p>
      </div>

      <div>
        <label
          htmlFor="company-website"
          className="block text-sm font-medium text-gray-700"
        >
          Coverbillede
        </label>
        <div className="relative mt-1 rounded-md shadow-sm">
          <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
            <span className="text-gray-500 sm:text-sm">https://</span>
          </div>
          <input
            type="text"
            name="company-website"
            id="company-website"
            className="block w-full rounded-md border-gray-300 pl-16 focus:border-indigo-500 focus:ring-indigo-500 sm:pl-14 sm:text-sm"
            placeholder="www.example.com/profile/avatar"
            {...register("jobProfile.coverImage", {})}
          />
        </div>
        <p className="mt-2 text-sm text-gray-500" id="email-description">
          Indsæt billede URL (link) fra eksempelvis Facebook eller LinkedIn.
        </p>
      </div>
    </div>
  )
}
//updateProfile.js
import { updateProfileInfo } from "@/utils/Fauna"
import { getSession } from "next-auth/react"

export default async (req, res) => {
  const session = await getSession({ req })
  if (!session) return res.status(401)

  const userId = session.user.id
  if (req.method !== "PUT") {
    return res.status(405).json({ msg: "Method not allowed" })
  }

  const { image, coverImage } =
    req.body
  try {
    const updated = await updateProfileInfo(
      userId,
      image,
      coverImage
    )
    return res.status(200).json(updated)
  } catch (err) {
    console.error(err)
    res.status(500).json({ msg: "Something went wrong." })
  }
  res.end()
}
//fauna.js
import * as Fauna from "faunadb"

const faunaClient = new Fauna.Client({
  secret: process.env.FAUNA_ADMIN_SECRET,
  scheme: "https",
  domain: "db.eu.fauna.com",
  port: 443,
})
const q = Fauna.query

const getUserById = async (id) => {
  const userData = await faunaClient.query(
    q.Get(q.Ref(q.Collection("users"), id))
  )
  delete userData.data.emailVerified
  delete userData.data.createdAt
  delete userData.data.updatedAt
  delete userData.data.ssn
  return userData.data
}

const updateProfileInfo = async (
  userId,
  image,
  coverImage
) => {
  return await faunaClient.query(
    q.Update(q.Ref(q.Collection("users"), userId), {
      data: {
        image,
        coverImage
      },
    })
  )
}

module.exports = {
  getUserById,
  updateProfileInfo
}

I would appreciate your help in identifying what I might be doing incorrectly.

Answer №1

Ensure that in your updateProfileInfo function within the fauna.js file, you include:

data: {
  jobProfile: {
    image,
    coverImage
  }
},

Instead of:

data: {
  image,
  coverImage
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatic line breaks within a JavaScript code can be achieved by using

I need help formatting this text: hello everyone. My name is PETER. hahahah ahahah .... If I have a fixed width, how can I automatically line break the text to look like this: hello everyone. My name is PETER. hahahah ahahah ...

Update WooCommerce Mini-cart with ajax refresh

I'm having an issue with my custom plugin where everything is working properly, except for the fact that the mini cart is not updating after adding items. I have tried various methods to trigger a refresh, but so far nothing has worked. Below is a sni ...

Discover the benefits of utilizing router.back() cascade in Next/React and how to effectively bypass anchor links

Currently, I am working on developing my own blog website using Next.js and MD transcriptions. The issue I am facing involves anchor links. All the titles <h1> are being converted into anchor links through the use of the next Link component: <Link ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...

Creating multiple tabs in PHP using the header function can be achieved by specifying the location in

I am attempting to open a new tab using Php code: header("location:print_register.php?recpt_no=".$recpt_no); In addition, I would like to open two tabs programmatically with the following code snippet: header("location:print_register.php?recpt_no=".$rec ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...

Using iScroll without animation by using scrolltoelement on an iPhone PhoneGap application

I've been working on an iOS PhoneGap app that uses Backbone and some other libraries. To handle scrolling, I implemented iScroll which has been functioning properly. However, I encountered a problem with the following code snippet: events: { &apo ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

having difficulty iterating through the data using map function

When attempting to use the map function in React Material UI to display an array of data in a select box, I encountered the error TypeError: Cannot read properties of undefined (reading 'map') while using the following code. Can anyone help me id ...

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...

What causes material-ui styling to flicker while moving between pages in Next.js?

Visit this link for more information Experience a unique button styling transition when moving from one page to another. Check out the code snippet here: Explore the code on GitHub ...

Express server experiencing a conflict with authentication sessions

Currently testing out a library found on this link and encountering a frustrating issue related to potential conflicts in cookie or header authentication. Upon logging into one account, everything runs smoothly. However, attempting to log into a different ...

Retrieving property values from an object across multiple levels based on property name

I have a complex object structure that contains price information at various levels. My goal is to retrieve all values from the Price property, regardless of their nesting within the object. var o = { Id: 1, Price: 10, Attribute: { Id: ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

What could be causing issues with my application when using server-side rendered styled-components with Next.js?

I am in need of assistance with an error I've encountered. Every time I try to access the homepage of my Next.js app, it breaks and displays a cannot read data map of undefined error. The browser consistently directs me to the _document.js file, but I ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...