DEV Community

Aman Pareek
Aman Pareek

Posted on • Edited on

2 1

Show image in react js from mongoDB data

Let say we fetching data from mongodb and storing the data in the values in react

Full example => here we have image in buffer so we use this imagefrombuffer package to convert buffer data to base64.

import React, { useEffect } from "react";
import { imagefrombuffer } from "imagefrombuffer"; //first import 

function author() {
  const [values, setvalues] = useState([]); // data

  const fetchauthor = async (e) => {
    let config = {
      method: "get",
      url: "http://localhost:8000/api/user/authorfind",
      headers: {
        Authorization: `Bearer ${thetoken()}`,
      },
    };

    await axios(config)
      .then((response) => {
        setvalues(response.data[0]); //setting data into values
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  useEffect(() => {
    fetchauthor();
  }, []);
  return (
    <>
   // imagefrombuffer  function usage to show image in react or next js from buffer
      <img 
        src={imagefrombuffer({
          type: values.profilephoto?.contentType,
          data: values.profilephoto?.data?.data,
        })}
      />
    </>
  );
}

export default author;
Enter fullscreen mode Exit fullscreen mode

use the function

<img src={imagefrombuffer({
          type: values.profilephoto?.contentType,
          data: values.profilephoto?.data?.data,
        })}
      />
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (8)

Collapse
 
amanp30 profile image
Aman Pareek

ansdgjn

Collapse
 
amanp30 profile image
Aman Pareek

another one

Collapse
 
amanp30 profile image
Aman Pareek

Image description

Collapse
 
amanp30 profile image
Aman Pareek

test comment

Collapse
 
amanp30 profile image
Aman Pareek

best one

Collapse
 
amanp30 profile image
Aman Pareek

mkasmdgk

Thread Thread
 
amanp30 profile image
Aman Pareek

ansdgnjasg

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay