#Next.js with ioredis implementation of textarea value change

9 messages · Page 1 of 1 (latest)

leaden kindle
reef berry
#

You need to create a post request API handler that will receive the text the user entered and persist it back to the redis cache

#

The flow would be:

  1. User types in API key
  2. User presses a button to save the value
  3. Make a post request to the API handler, including the new value for the key
  4. Your API handler saves the new value into redis
#

@leaden kindle Also, you probably don't want to create a new redis connection inside of getServerSideProps. That function gets executed once for every incoming request. You'd be creating a new connection to redis for every request. Most redis servers cap the number of active connections. In addition, you're not closing the connection. Best solution would be to move the connection creation outside of getServerSideProps

leaden kindle
# reef berry The flow would be: 1. User types in API key 2. User presses a button to save the...

Would the following example work?
As to my understanding, I believe it should work.

import Redis from "ioredis";
import React, { useState } from "react";

/* ---------------------------------------------------------------------------------------------------------- */

// Create a Redis connection outside of any request handlers
const redis = new Redis({
  host: "redis", // Redis host
  port: "6379", // Redis port
});

/* ---------------------------------------------------------------------------------------------------------- */

export const getServerSideProps = async () => {
  // Get a key from Redis
  const apiToken = await redis.get("apiToken");

  // Return the data as a prop
  return {
    props: {
      apiToken,
    },
  };
};

/* ---------------------------------------------------------------------------------------------------------- */

export default function Dashboard({ apiToken }) {
  const [localApiToken, setApiToken] = useState(apiToken);

  const handleApiTokenChange = (e) => {
    // Set the value of the textarea element in the component's state
    setApiToken(e.target.value);
  };

  const handleSave = async () => {
    // Set the value of the 'apiToken' key in Redis
    await redis.set("apiToken", localApiToken);
  };

  return (
    <div>
      <textarea
        className="ai-keyarea"
        placeholder="Paste in your timezone."
        required
        rows="3"
        cols="45"
        value={localApiToken}
        onChange={handleApiTokenChange}
      />
      <button onClick={handleSave}>Save</button>
    </div>
  );
}

/* ---------------------------------------------------------------------------------------------------------- */

reef berry
#

@leaden kindle no, you can't set values to redis from inside of a component

reef berry
#

the click event handler is being executed in the users browser. The user's browser doesn't have access to your redis server.